I have been trying to upload a multipart file in my Java Spring MVC Web Application using a POST REST service method. I have using the following REST service method to upload the file and this works fine when i choose the file using Postman REST service.
@RequestMapping(value="/upload", method=RequestMethod.POST)
public @ResponseBody String handleFileUpload( @RequestParam("file") MultipartFile file, ModelMap model)
{
//codes
}
But when i tried to pass the multipart file as parameter to a POST REST service method in the controller. Its not working fine. So how can i pass multipart file as a queryparam to a POST REST service method.
In my controller class I have:
@RequestMapping(value = "/upload-image", method = RequestMethod.POST)
public String uploadProfileImage(@RequestParam("fileUpload") MultipartFile fileUpload, Model model, HttpServletRequest request, HttpServletResponse response)
{
// codes
}
I have the following bean in my root-context.xml file
<bean id="multipartResolver"
class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
</bean>
Any help is appreciated.
It is easy and a little bit strange. Do use @PathVariable
instead of @RequestParam
. I faced with this situation couple month ago. I do not know why it so, but snippet below works in my project.
@ResponseBody
@RequestMapping(method = RequestMethod.POST, value = "/upload-image", consumes = MULTIPART_FORM_DATA_VALUE, produces = APPLICATION_JSON_VALUE)
public String uploadProfileImage(@PathVariable("fileUpload") MultipartFile file) {
// ...
}
Look at JerseyRestClientMultipartUpload.java to get example how to send MultiPart
using Jersey
.
final MultiPart multiPart = new FormDataMultiPart()
.field("description", "Picture of Jabba the Hutt", MediaType.TEXT_PLAIN_TYPE)
.field("characterProfile", jsonToSend, MediaType.APPLICATION_JSON_TYPE)
.field("filename", fileToUpload.getName(), MediaType.TEXT_PLAIN_TYPE)
.bodyPart(fileDataBodyPart);
multiPart.setMediaType(MediaType.MULTIPART_FORM_DATA_TYPE);
// POST request final
final WebResource resource = client.resource(API_URI)
ClientResponse response = resource.type("multipart/form-data").post(ClientResponse.class, multiPart);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.