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