【问题标题】:Java+Spring: Can i upload file if I have path without HttpRequest?Java+Spring:如果我有没有 HttpRequest 的路径,我可以上传文件吗?
【发布时间】:2012-03-28 11:37:11
【问题描述】:

我正在这样做

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

【问题讨论】:

  • 您尚未将multipartFile 分配给任何内容。你怎么能指望它不会抛出 NPE?

标签: java spring upload


【解决方案1】:

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

【讨论】:

  • 如果我只有路径,应该如何初始化 multipartFile?
  • 我有列表文件名,用户选择 1 个文件(单选按钮),我必须上传这个文件。我在控制器中只收到名称文件(字符串)和路径(字符串)。我不使用 选择文件,这可能吗?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-11-22
  • 1970-01-01
  • 2016-03-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多