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

时间:2012-03-28 11:37:12

标签: java spring upload

我这样做

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

1 个答案:

答案 0 :(得分:4)

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();