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上传多部分文件全部内容,希望文章能够帮你解决android – 使用OkHttp Spring上传多部分文件所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)