REST fileupload in Spring controller using multipa

2019-08-07 05:15发布

Is it possible to upload file with additional data (like description etc.) with use of multipart/form-data? I'm using backbone.js in my frontend and I call REST api with it (jQuery). I don't use any view resolver but I want to somehow pass my file to controller like:

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

so that uploadItem stores:

private String desctiption;
private List<CommonsMultipartFile> fileData;

But I'm not adding (and I can't) this to my model.

Of course I'm also interested if it's possible to have controller like:

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

1条回答
叼着烟拽天下
2楼-- · 2019-08-07 06:03

Yes you can pass the other form fields also along with multi part data. You can check the field name and use it like. (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());
   }
  }
查看更多
登录 后发表回答