Issue
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;
}
Solution
You can get a MultipartFile more easier:
@RequestMapping(value = "/upload", method = RequestMethod.POST)
public String upload(@RequestParam("qqfile") MultipartFile file) throws IOException {
if (!file.isEmpty()) {
// ...
}
return "failure";
}
And then, with OkHttp:
RequestBody body = new MultipartBuilder()
.addFormDataPart("qqfile", filename, RequestBody.create(MediaType.parse("media/type"), new File(filename)))
.type(MultipartBuilder.FORM)
.build();
Request request = new Request.Builder()
.url("/path/to/your/upload")
.post(body)
.build();
OkHttpClient client = new OkHttpClient();
Response response = client.newCall(request).execute();
That worked fine to me.
Be careful with MediaType.parse(filename), you must pass a valid type like text/plain, application/json, application/xml...
Answered By - Marcus Henrique