繁体   English   中英

Java + Spring:如果我有没有HttpRequest的路径,可以上传文件吗?

[英]Java+Spring: Can i upload file if I have path without HttpRequest?

我正在这样做

protected ModelAndView onSubmit(HttpServletRequest request,
       HttpServletResponse response, Object command, BindException errors)
       throws Exception {
    MultipartFile multipartFile = null;
    File destFile = new File(
            "/home/stas/eclipse/" + request.getParameter("fileName"));
multipartFile.transferTo(destFile);

但是我有例外

27.03.2012 20:39:45 org.apache.catalina.core.StandardWrapperValve invoke 
SEVERE: Servlet.service() for servlet [springapp] in context with 
    path [/springapp] threw exception [Request processing failed; 
    nested exception is java.lang.NullPointerException] with root cause
    java.lang.NullPointerException

NullPointerException非常明显:

MultipartFile multipartFile = null;
File destFile = new File("/home/stas/eclipse/"+request.getParameter("fileName"));
multipartFile.transferTo(destFile);   <-----Exception

multipartFile变量永远不会初始化,并且在首次访问时会引发NPE。

您可以使用以下方法从请求中获取所有上传的文件:

public ModelAndView onSubmit(HttpServletRequest request, /*...*/) {
  MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest)request;
  Map<String, MultipartFile> files = multipartRequest.getFileMap();

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM