android – 使用OkHttp Spring上传多部分文件

我最近切换到了OkHttp.切换后,下面的代码执行上传.

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();

如果比较图像,第二个图像的multipartFiles大小= 0.它应该是size = 1.如何使用OkHttp正确填充multipartHttpRequest以使服务器接受成功上传?

控制器代码

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;
}
最佳答案
您可以更轻松地获得MultipartFile:

@RequestMapping(value = "/upload", method = RequestMethod.POST)
public String upload(@RequestParam("qqfile") MultipartFile file) throws IOException {
    if (!file.isEmpty()) {
        // ...
    }
    return "failure";
}

然后,用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();

这对我很好.

注意MediaType.parse(filename),你必须传递一个有效的类型,如text / plain,application / json,application / xml …

转载注明原文:android – 使用OkHttp Spring上传多部分文件 - 代码日志