I recently switched to OkHttp
. After the switch, the code below does the upload.
RequestBody requestBody = new MultipartBuilder()
.type(MultipartBuilder.FORM)
.addPart(
Headers.of("Content-Disposition", "form-data; name=\"qqfile\""),
RequestBody.create(
MediaType.parse(filename),
new File(filename)))
.build();
If you compare images, the second image has multipartFiles
size = 0
. It should be of size = 1
. How to populate multipartHttpRequest
correctly using OkHttp
to make server accept successful upload?
Controller code
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.springframework.http.MediaType;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.util.WebUtils;
@RequestMapping (
method = RequestMethod.POST,
value = "/upload",
produces = MediaType.APPLICATION_JSON_VALUE + ";charset=UTF-8"
)
public String upload(
HttpServletRequest request,
HttpServletResponse response
) throws IOException {
boolean isMultipart = ServletFileUpload.isMultipartContent(request);
if (isMultipart) {
MultipartHttpServletRequest multipartHttpRequest =
WebUtils.getNativeRequest(request, MultipartHttpServletRequest.class);
final List<MultipartFile> files = multipartHttpRequest.getFiles("qqfile");
if (files.isEmpty()) {
LOG.error("qqfile name missing in request or no file uploaded");
return some error code here
}
MultipartFile multipartFile = files.iterator().next();
//process file code below
}
return failure;
}
You can get a MultipartFile more easier:
And then, with OkHttp:
That worked fine to me.
Be careful with MediaType.parse(filename), you must pass a valid type like text/plain, application/json, application/xml...