編輯:關於 Android 程式設計
由於 gif 圖較大,我把圖放在了 GitHub 上,博客裡若顯示不出來可以點擊傳送門查看。本文代碼寫於 md,可讀性一般,敬請諒解。
上一篇我們介紹了 Retrofit 的文件上傳、下載以及進度監聽,這篇我們來聊聊批量上傳與上傳進度的監聽。
要實現批量上傳,可以借鑒 HTML 中借助 Form 表單的思路,在 Retrofit 裡同樣通過 Form 表單來完成。
其中 action 是表單提交地址,enctype 表示表單的編碼方式,multipart/form-data 表示有文件上傳;file input 標簽的 name 必須是 xxx[] 的格式,代表數組中的一個元素(去掉 [],PHP 端就收不到了)。
$error) { if ( $error == UPLOAD_ERR_OK ) { //PHP常量UPLOAD_ERR_OK=0,表示上傳沒有出錯 $temp_name = $fileArray['tmp_name'][$key]; $file_name = $fileArray['name'][$key]; move_uploaded_file($temp_name, $upload_dir.$file_name); echo '上傳[文件'.$file_name.']成功!
'; }else { echo '上傳[文件'.$key.']失敗!
'; } }
所有文件都存在 $_FILES 全局變量中,多個文件時格式如下:
array(1) { ["file"]=> array(5) { ["name"]=> array(3) { [0]=> string(5) "1.txt" [1]=> string(5) "2.txt" [2]=> string(5) "3.txt" } ["type"]=> array(3) { [0]=> string(10) "text/plain" [1]=> string(10) "text/plain" [2]=> string(10) "text/plain" } ["tmp_name"]=> array(3) { [0]=> string(27) "C:\Windows\Temp\phpB829.tmp" [1]=> string(27) "C:\Windows\Temp\phpB82A.tmp" [2]=> string(27) "C:\Windows\Temp\phpB82B.tmp" } ["error"]=> array(3) { [0]=> int(0) [1]=> int(0) [2]=> int(0) } ["size"]=> array(3) { [0]=> int(11) [1]=> int(13) [2]=> int(13) } }
我們需要遍歷數組,把每個文件寫入指定位置。
* 我對 PHP 只懂皮毛,上面若有描述不清或不之處,歡迎指正。*

博客看不到?點我看圖
``` @Multipart @POST("/fileabout.php") Call upload_2(@Part("filedes") String des,@Part("file[]\"; filename=\"1.txt") RequestBody imgs,@Part("file[]\"; filename=\"2.txt") RequestBody imgs_2,@Part("file[]\"; filename=\"3.txt") RequestBody imgs_3);
這種把文件名寫死在接口裡的做法靈活性差,沒有實用價值。注意 file[]、注意 file[]、注意 file[]。
發送請求的相關代碼:
File file = new File(Environment.getExternalStorageDirectory() + "/" + "1.txt"); File file2 = new File(Environment.getExternalStorageDirectory() + "/" + "2.txt"); File file3 = new File(Environment.getExternalStorageDirectory() + "/" + "3.txt"); final RequestBody requestBody = RequestBody.create(MediaType.parse("multipart/form-data"),file); final RequestBody requestBody2 = RequestBody.create(MediaType.parse("multipart/form-data"),file2); final RequestBody requestBody3 = RequestBody.create(MediaType.parse("multipart/form-data"),file3); Call model = service.upload_2("this is txt",requestBody,requestBody2,requestBody3);
這種寫法缺乏靈活性,因此不具備使用價值,我們需要更好的方案。
相應的接口改用 @PartMap:
@Multipart @POST("/fileabout.php") Call upload_3(@Part("filedes") String des,@PartMap Map params);
這樣就能靈活配置 part 了,客戶端可以通過下面的方式進行配置:
Map params = new HashMap(); params.put("file[]\"; filename=\""+file.getName()+"", requestBody); params.put("file[]\"; filename=\""+file2.getName()+"", requestBody2); params.put("file[]\"; filename=\""+file3.getName()+"", requestBody3); Call model = service.upload_3("hello",params);
靈活性是不是提升了很多?這樣才像真正的 form 表單,可以隨意配置。

博客看不到?點我看圖
到這裡批量上傳就完成了,如果你有更好的方案,歡迎交流。
剛接觸這個問題時完全沒思路,於是去翻 GitHub 上官方給出的幾個類。仔細觀察 converter 相關的類可以發現,其中出現了 RequestBody——這讓我靈感一現:既然下載能監聽,上傳也一定能如法炮製,把這個類改造一下即可。
下圖展示了 converter 中 RequestBody 的相關結構:

博客看不到?點我看圖

博客看不到?點我看圖
第一步,拋棄內部自動生成的 RequestBody,改為手動傳入,去掉下面這行:
final RequestBody realBody = delegate.convert(value)
第二步,return new RequestBody() 相關代碼裡缺少長度信息,需要補上:
@Override public long contentLength() throws IOException { return requestBody.contentLength(); }
第三步,模仿下載的思路,寫出上傳的過程:
@Override public void writeTo(BufferedSink sink) throws IOException{ // realBody.writeTo(sink); if (bufferedSink == null) { //包裝 bufferedSink = Okio.buffer(sink(sink)); } //寫入 requestBody.writeTo(bufferedSink); //必須調用flush,否則最後一部分數據可能不會被寫入 bufferedSink.flush(); } private Sink sink(Sink sink) { return new ForwardingSink(sink) { //當前寫入字節數 long bytesWritten = 0L; //總字節長度,避免多次調用contentLength()方法 long contentLength = 0L; @Override public void write(Buffer source, long byteCount) throws IOException { super.write(source, byteCount); if (contentLength == 0) { //獲得contentLength的值,後續不再調用 contentLength = contentLength(); } //增加當前寫入的字節數 bytesWritten += byteCount; //回調 listener.onProgress(bytesWritten, contentLength, bytesWritten == contentLength); } }; }
改造後,整個類變成了下面的樣子(也可到我的 GitHub 下載):
public class ChunkingConverterFactory extends Converter.Factory { @Target(PARAMETER) @Retention(RUNTIME) @interface Chunked { } private BufferedSink bufferedSink; private final RequestBody requestBody; private final ProgressListener listener; public ChunkingConverterFactory(RequestBody requestBody,ProgressListener listener){ this.requestBody = requestBody; this.listener = listener ; } @Override public Converter, RequestBody> requestBodyConverter(Type type, Annotation[] parameterAnnotations, Annotation[] methodAnnotations, Retrofit retrofit) { boolean isBody = false; boolean isChunked = false; for (Annotation annotation : parameterAnnotations){ isBody |= annotation instanceof Body; isChunked |= annotation instanceof Chunked; } final Converter
和下載一樣,通過 Builder 來 build 對象(也可以直接 new,但 RequestBody 得寫在前面,看起來有點怪)。完整代碼如下:
private void uploadProgress(){ Retrofit.Builder builder = new Retrofit.Builder() .baseUrl("https://192.168.56.1"); File file = new File(Environment.getExternalStorageDirectory() + "/" + "text_img.png"); final RequestBody requestBody = RequestBody.create(MediaType.parse("multipart/form-data"),file); uploadfileApi api = builder.addConverterFactory(new ChunkingConverterFactory(requestBody, new ProgressListener() { @Override public void onProgress(long progress, long total, boolean done) { Log.e(TAG, "onProgress: 這是上傳的 " + progress + "total ---->" + total ); Log.e(TAG, "onProgress: " + Looper.myLooper()); } })).addConverterFactory(GsonConverterFactory.create()).build().create(uploadfileApi.class); Call model = api.upload("hh",requestBody); model.enqueue(new Callback() { @Override public void onResponse(Call call, Response response) { } @Override public void onFailure(Call call, Throwable t) { } }); }

博客看不到?點我看圖
掌握了單個文件的上傳進度監聽,多個文件的做法也就不言自明——多添加幾個轉換器即可。
Retrofit 確實很強大。有朋友希望我配合 RxJava 再寫一篇,別急,先把基礎用法那篇看熟再說。還有很多功能沒講到,大家有需求可以留言,我們一起研究。
RecyclerView 詳解:一套代碼實現 ListView、GridView 與瀑布流
RecyclerView 是 Google 推出的、用來取代 ListView 與 GridView 的新一代容器。它只專注於「回收複用」,而把布局交给 LayoutMa
Android Studio 進階詳細配置:提升開發效率的實用技巧
Android Studio 是 Android 開發中最常用的 IDE 之一。除了基礎功能,合理的進階配置能顯著提升閱讀代碼、編寫代碼與排查問題的效率。以下幾項配置非常
Android 開發者頭條實戰(一):引導啟動頁的實現
廢話不多說,本文直接帶你動手實現「開發者頭條」APP 的引導啟動頁。 一、效果預覽 從效果圖可以看出,整個滑動界面由 ViewPager 實現,再監聽滑動事件來切換底部
用 ExpandableListView 嵌套實作三級樹選單
標準的 ExpandableListView 只有兩層(群組與子項),要做三級樹(公司 → 部門 → 員工)就需要在子項的位置再嵌一個 ExpandableListVie