'REST fileupload in Spring controller using multipart/form-data
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)
Solution 1:[1]
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());
}
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Martijn Pieters |
