【问题标题】:REST fileupload in Spring controller using multipart/form-data使用 multipart/form-data 在 Spring 控制器中上传 REST 文件
【发布时间】:2014-01-04 20:37:20
【问题描述】:

是否可以使用multipart/form-data 上传带有附加数据(如描述等)的文件?我在前端使用backbone.js,并用它(jQuery)调用REST api。 我不使用任何视图解析器,但我想以某种方式将我的文件传递给控制器​​,例如:

@RequestMapping(value = "/image/upload", method = RequestMethod.POST)
public String upload(UploadItem uploadItem, HttpSession session)

以便 uploadItem 存储:

private String desctiption;
private List<CommonsMultipartFile> fileData;

但我不会(也不能)将它添加到我的模型中。

当然我也很感兴趣,如果有可能有这样的控制器:

@RequestMapping(value = "/image/upload", method = RequestMethod.POST)
public String upload(someFileType uploadItem, String desctiption)

【问题讨论】:

  • 查看 mkyong 使用 spring MVC mkyong.com/spring-mvc/spring-mvc-file-upload-example 上传文件的教程,它使用表单提交而不是 ajax 请求,但其余的应该适用。您是否看到错误消息?
  • 但它使用jsp。是否可以只创建这样的表单html?
  • 是的,普通的html表单或者ajax请求也可以,最后jsp在服务器端被解析并变成普通的html表单。
  • 好的,我搞定了,非常感谢!
  • 请将其添加到您如何解决的答案中并将其标记为答案

标签: spring rest backbone.js file-upload


【解决方案1】:

是的,您也可以将其他表单字段与多部分数据一起传递。您可以检查字段名称并像使用它一样。 (if (item.getName().equals("desctiption")))。

try {
    // Parse the request
    List items = upload.parseRequest(request);
    Iterator iterator = items.iterator();
    while (iterator.hasNext()) {
     FileItem item = (FileItem) iterator.next();
     if (!item.isFormField() && !item.getName().equals("")) {
      String fileName = item.getName();
      String root = context.getRealPath("/");
      File path = new File(root + "/uploads");
      if (!path.exists()) {
       boolean status = path.mkdirs();
      }

      File uploadedFile = new File(path + "/" + fileName);
      fileNames.add(fileName);
      System.out.println("File Path:-"
        + uploadedFile.getAbsolutePath());

      item.write(uploadedFile);
     }
    }
   } catch (FileUploadException e) {
    System.out.println("FileUploadException:- " + e.getMessage());
   } catch (Exception e) {
    System.out.println("Exception:- " + e.getMessage());
   }
  }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-12-14
    • 1970-01-01
    • 2015-10-23
    • 1970-01-01
    • 2022-01-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多