Multipart file upload with OkHttp + Spring

6.2k views Asked by At

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?

Correct In-Correct

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;
}
2

There are 2 answers

0
Marcus Henrique On BEST ANSWER

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...

0
자몽. On
Builder requestBodyBuilder = new MultipartBody.Builder()
                        .setType(MultipartBody.FORM);
File file= new File(FILE_PATH + FILE_NAME);
requestBodyBuilder.addFormDataPart("file", FILE_NAME, RequestBody.create(MultipartBody.FORM, file));

fileVO.getOriginalFlnm()

you can omission this field.

And also you have to set 'MultipartHttpServletRequest' parameter AND consumes, produces in header

@PostMapping(path = "/save", consumes = "multipart/*", produces = "application/json;charset=utf-8")
public boolean CONTROLLER(MultipartHttpServletRequest request, @RequestParam Map<String, Object> param) {
    boolean result = SERVICE.save(request, param);
    return result;
}