[英]How To Pass Multipart Image File as parameter to a POST REST Service
I have been trying to upload a multipart file in my Java Spring MVC Web Application using a POST REST service method. 我一直在尝试使用POST REST服务方法在Java Spring MVC Web应用程序中上传多部分文件。 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.
我已使用以下REST服务方法上传文件,并且当我使用Postman REST服务选择文件时,此方法工作正常。
@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. 但是,当我尝试将multipart文件作为参数传递给控制器中的POST REST服务方法时。 Its not working fine.
它不能正常工作。 So how can i pass multipart file as a queryparam to a POST REST service method.
因此,如何将多部分文件作为queryparam传递给POST REST服务方法。
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 我的root-context.xml文件中有以下bean
<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
. 不要使用
@PathVariable
而不是@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
. 查看JerseyRestClientMultipartUpload.java以获取示例如何使用
Jersey
发送MultiPart
示例。
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);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.