Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multipart file upload with OkHttp + Spring

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?

CorrectIn-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;
}
like image 776
java_dude Avatar asked Jun 08 '15 11:06

java_dude


2 Answers

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

like image 77
Marcus Henrique Avatar answered Sep 27 '22 19:09

Marcus Henrique


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;
}
like image 37
자몽. Avatar answered Sep 27 '22 18:09

자몽.