okhttp不用说,很火的网络库。今天说一下上传图片的问题。
搜索一下,很有很多文章介绍怎样上传图片,到本篇文章为止我看到都是用的MultipartBuilder构造器,但是在3.0以上版本中MultipartBuilder已被替代,官方说明如下
Form and Multipart bodies are now modeled. We've replaced the opaque FormEncodingBuilder with the more powerful FormBody and FormBody.Builder combo. Similarly we've upgraded MultipartBuilder into MultipartBody,MultipartBody.Part, and MultipartBody.Builder.
说的是MultipartBuilder已被升级成
MultipartBody
,
MultipartBody.Part
和
MultipartBody.Builder
.
stackoverflow上面也有回答
Form and Multipart bodies are now modeled. We've replaced the opaque FormEncodingBuilder with the more powerful FormBody and FormBody.Builder combo. Similarly we've upgraded MultipartBuilder into MultipartBody, MultipartBody.Part, and MultipartBody.Builder.
http://stackoverflow.com/questions/34676044/multipartbuilder-cant-be-resolved-in-okhttp3-0-0-rc1
既然MultipartBuilder不可用了,那么用MultipartBuilder上传图片的方式也不可用了。经过查看官方Demo和自己测试,用以下方式即可在3.0以上版本中上传图片:
MultipartBody body = new MultipartBody.Builder("AaB03x")
.setType(MultipartBody.FORM)
.addFormDataPart("files", null, new MultipartBody.Builder("BbC04y")
.addPart(Headers.of("Content-Disposition", "form-data; filename=\"img.png\""),
RequestBody.create(MediaType.parse("image/png"), new File(path)))
.build())
.build();
其中new File(path)即是图片文件。如果上传多张,则只要多次addFormDataPart即可,构造好body后使用post方式正常提交就可以上传图片至服务器。
-------------------------------------- 更新 -------------------------------------
开发过程中,有时候需要直接把内存中的一张图片上传到服务器,可以采用二进制流的方式。
ByteArrayOutputStream bos = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, bos);
MultipartBody body = new MultipartBody.Builder("AaB03x")
.setType(MultipartBody.FORM)
.addFormDataPart("files", null, new MultipartBody.Builder("BbC04y")
.addPart(Headers.of("Content-Disposition", "form-data; filename=\"img.png\""),
RequestBody.create(MediaType.parse("image/png"), bos.toByteArray()))
.build())
.build();