[英]Spring boot API which accepts JSON (mandatory) and multipart file (optional)
I want to create an API which accepts both object (as JSON) and allows to upload multiple files. 我想创建一个接受两个对象(作为JSON)并允许上传多个文件的API。
I am using spring boot at tried code below 我在下面的尝试代码中使用Spring Boot
@RequestMapping(value = "/some-action", method = RequestMethod.POST)
public void post(@RequestPart(value = "jsonString") String jsonAsString,
@RequestPart(value = "file", required = false) MultipartFile[] files,
HttpServletResponse response)
I am accepting jsonAsString
because I was not able to accept object instead. 我接受jsonAsString
因为我无法接受对象。 So, for temporary solution I am passing json string. 因此,对于临时解决方案,我传递了json字符串。
Now, as you can see in code above that for file
I have set required
to false
. 现在,如您在上面的代码中看到的那样,对于file
我将required
设置为false
。 But, I am getting server error when I am not passing any file. 但是,当我不传递任何文件时,出现服务器错误。
Below is my request body. 以下是我的请求正文。
--ARCFormBoundaryer1k80a5e1att9
Content-Disposition: form-data; name="text"
"{"key":"value"}"
--ARCFormBoundaryer1k80a5e1att9--
Below is error I am getting. 以下是我遇到的错误。 org.apache.tomcat.util.http.fileupload.MultipartStream$MalformedStreamException: Stream ended unexpectedly at org.apache.tomcat.util.http.fileupload.MultipartStream.readHeaders(MultipartStream.java:487) ~[tomcat-embed-core-8.0.23.jar:8.0.23] at org.apache.tomcat.util.http.fileupload.FileUploadBase$FileItemIteratorImpl.findNextItem(FileUploadBase.java:889) ~[tomcat-embed-core-8.0.23.jar:8.0.23] at org.apache.tomcat.util.http.fileupload.FileUploadBase$FileItemIteratorImpl.<init>(FileUploadBase.java:854) ~[tomcat-embed-core-8.0.23.jar:8.0.23] at org.apache.tomcat.util.http.fileupload.FileUploadBase.getItemIterator(FileUploadBase.java:256) ~[tomcat-embed-core-8.0.23.jar:8.0.23] at org.apache.tomcat.util.http.fileupload.FileUploadBase.parseRequest(FileUploadBase.java:280) ~[tomcat-embed-core-8.0.23.jar:8.0.23] at org.apache.catalina.connector.Request.parseParts(Request.java:2730) ~[tomcat-embed-core-8.0.23.jar:8.0.23]
Please suggest me what can I do to fulfill my requirement. 请建议我该怎么做才能满足我的要求。
I think I understand what you are trying to do. 我想我知道您要做什么。 We tried something similar. 我们尝试了类似的方法。 Unfortunately because of the different way file uploads get handled than normal data payloads on a POST, you will probably have to use a different URL. 不幸的是,由于文件上传的处理方式与POST上的常规数据有效负载不同,因此您可能必须使用不同的URL。
We got it working in one browser (can't remember which), but it was flakey. 我们让它在一个浏览器中运行(不记得是哪个浏览器),但这是易碎的。 It's kind of like overloading a URL. 这有点像重载URL。
Sorry, but I hope this does disappoint you too much... 对不起,但是我希望这会让您失望太多...
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.