Spring控制器中的REST文件上载使用multipart / form-data

时间:2014-01-04 20:37:20

标签: spring rest backbone.js file-upload

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

@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)

1 个答案:

答案 0 :(得分:0)

是的,您也可以传递其他表单字段以及多部分数据。您可以检查字段名称并使用它。 ( if(item.getName()。equals(&#34; desctiption&#34;)))。

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