Android 網絡開源庫-Retrofit(三) 批量上傳及上傳進度監聽

  • 由于gif圖太大的原因,我將圖放在了github,如果博客中顯示不出來圖,傳送門
  • 由于我是事先寫在md上的,導致代碼的可讀性差,大家將就著看吧。

1. 前言

在上一篇博客中,我們介紹了Retrofit的文件上傳,文件下載以及進度監聽,這篇博客我們來了解下批量上傳以及上傳進度的監聽。

2.批量上傳

要想實現批量上傳,我們要考慮下HTML中實現批量上傳的方法,借助Form表單,所以,我們也可以通過借助Form表單來實現批量上傳。

2.1 HTML FORM 表單的寫法

<html>
<body>

<form action="http://localhost/fileabout.php" enctype="multipart/form-data" method="post">
  <p>First name: <input type="file" name="file[]" id="name1" /></p>
  <p>First name: <input type="file" name="file[]" id="name2" /></p>
  <p>First name: <input type="file" name="file[]" id="name3" /></p>
  <input type="submit" value="Submit" />
</form>

</body>
</html>
  • action form表單提交的地址
  • enctype 表示如何對表單進行編碼,multipart/form-data表示有file
  • input標簽中的name必須是xxx[]的格式,表示是數組中的一個元素(ps:我也不知道正確不正確,但是去掉[],我php就接收不到了)

2.2 php接收代碼

<?php   
    header('Content-Type:text/html;charset=utf-8');
    $fileArray = $_FILES['file'];//獲取多個文件的信息,注意:這里的鍵名不包含[]

    $upload_dir = "D:\WWW"."\\"; //保存上傳文件的目錄
    foreach ( $fileArray['error'] as $key => $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.']成功!<br/>';
        }else {
            echo '上傳[文件'.$key.']失敗!<br/>';
        }
    }
  • 所有的文件都會存在$_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只會點皮毛中的皮毛,所以上面有的內容可能描述的不清楚或者不正確,請指出 **
** 由于我php只會點皮毛中的皮毛,所以上面有的內容可能描述的不清楚或者不正確,請指出 **
** 由于我php只會點皮毛中的皮毛,所以上面有的內容可能描述的不清楚或者不正確,請指出 **

2.3 演示結果

博客看不到?點我看圖

2.4 Android中的實現-方法一(low)

@Multipart
@POST("/fileabout.php")
Call<String> 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);

 * 在api接口中寫死,靈活性差,沒有實用價值
 * **注意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<String> model = service.upload_2("this is txt",requestBody,requestBody2,requestBody3);


上面的這種辦法沒有靈活性科研,所以是不具有使用價值的,那么,我們需要用下面這種辦法。

#### 2.5 Android中的實現方法(二) 
相應的api接口變成了這個樣子

@Multipart
@POST("/fileabout.php")
Call<String> upload_3(@Part("filedes") String des,@PartMap Map<String,RequestBody> params);

 * 這樣 我們就可以靈活的配置part了

那么,客戶端就可以通過下面這種方法進行配置了,

Map<String,RequestBody> params = new HashMap<String, RequestBody>();
params.put("file[]"; filename=""+file.getName()+"", requestBody);
params.put("file[]"; filename=""+file2.getName()+"", requestBody2);
params.put("file[]"; filename=""+file3.getName()+"", requestBody3);
Call<String> model = service.upload_3("hello",params);

靈活性是不是有所提升?這樣才像form表單,可以隨意配置了。

#### 2.6 結果展示
![](https://github.com/Guolei1130/ATips/blob/master/image/retrofit/duo%20upload%202.gif?raw=true)
[博客看不到?點我看圖](https://github.com/Guolei1130/ATips/blob/master/image/retrofit/duo%20upload%202.gif)
到這里,我們的批量上傳就結束了,如果各位朋友有什么更好的辦法,請教教我。。。

### 3.上傳進度的監聽
當想到這個問題的時候,完全沒有思路,那就尷尬了。仔細想想,好吧,還是沒有思路,那么,咱們去看看github上官方給出的幾個類,。[就看這個類 就看這個類](https://github.com/square/retrofit/blob/master/samples/src/main/java/com/example/retrofit/ChunkingConverter.java)
恩,我給出2張圖,大家自己觀察下
![](https://github.com/Guolei1130/ATips/blob/master/image/retrofit/upload_pro_1.png?raw=true)
[博客看不到?點我看圖](https://github.com/Guolei1130/ATips/blob/master/image/retrofit/upload_pro_1.png)
![](https://github.com/Guolei1130/ATips/blob/master/image/retrofit/upload_pro_2.png?raw=true)
[博客看不到?點我看圖](https://github.com/Guolei1130/ATips/blob/master/image/retrofit/upload_pro_2.png)
發現沒?轉化器中出現了RequestBody,這讓我瞬間有了想法,沒錯,我們模仿下載的辦法,同樣的,將這個類改造下。

#### 3.1 改造ChunkingConverterFactory
首先,我們拋棄里面的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上將這個類下載來下。[鏈接地址](https://github.com/Guolei1130/ATips/blob/master/code/retrofit/ChunkingConverterFactory.java)

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<Object,RequestBody> delegate = retrofit
            .nextRequestBodyConverter(this,type,parameterAnnotations,methodAnnotations);

    return new Converter<Object, RequestBody>() {
        @Override
        public RequestBody convert(Object value) throws IOException {


            return new RequestBody() {
                @Override
                public MediaType contentType() {
                    return requestBody.contentType();
                }


                @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);
                        }
                    };
                }
            };
        }
    };
}

}


#### 3.2 監聽上傳進度
像下載一下,我們還是通過builder去build對象,當然 也可以使用普通的方法,但是得RequestBody 寫在前面,這樣看起來有點怪怪的。整個代碼如下

private void uploadProgress(){
Retrofit.Builder builder = new Retrofit.Builder()
.baseUrl("http://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<String> model = api.upload("hh",requestBody);
model.enqueue(new Callback<String>() {
@Override
public void onResponse(Call<String> call, Response<String> response) {

        }

        @Override
        public void onFailure(Call<String> call, Throwable t) {

        }
    });
}
#### 3.3 結果演示
![](https://github.com/Guolei1130/ATips/blob/master/image/retrofit/upload_progress.gif?raw=true)
[博客看不到?點我看圖](https://github.com/Guolei1130/ATips/blob/master/image/retrofit/upload_progress.gif)
#### 3.4 批量上傳的進度監聽
我們知道了如何監聽單個文件的上傳進度,多個文件,恩,就不說了啊,(添加多個轉換器嘍)。

### 4. 總結
Retrofit很強大 很強大,有的同學想讓我配合上Rxjava寫,哎,朋友,給個面子啊,好歹把我第一篇基礎用法看看哪。還剩下許多許多的功能沒介紹,看朋友們有什么需求了,可以給我留言,完了一起研究啊。
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。
  • 序言:七十年代末,一起剝皮案震驚了整個濱河市,隨后出現的幾起案子,更是在濱河造成了極大的恐慌,老刑警劉巖,帶你破解...
    沈念sama閱讀 229,001評論 6 537
  • 序言:濱河連續發生了三起死亡事件,死亡現場離奇詭異,居然都是意外死亡,警方通過查閱死者的電腦和手機,發現死者居然都...
    沈念sama閱讀 98,786評論 3 423
  • 文/潘曉璐 我一進店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人,你說我怎么就攤上這事。” “怎么了?”我有些...
    開封第一講書人閱讀 176,986評論 0 381
  • 文/不壞的土叔 我叫張陵,是天一觀的道長。 經常有香客問我,道長,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 63,204評論 1 315
  • 正文 為了忘掉前任,我火速辦了婚禮,結果婚禮上,老公的妹妹穿的比我還像新娘。我一直安慰自己,他們只是感情好,可當我...
    茶點故事閱讀 71,964評論 6 410
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著,像睡著了一般。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發上,一...
    開封第一講書人閱讀 55,354評論 1 324
  • 那天,我揣著相機與錄音,去河邊找鬼。 笑死,一個胖子當著我的面吹牛,可吹牛的內容都是我干的。 我是一名探鬼主播,決...
    沈念sama閱讀 43,410評論 3 444
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了?” 一聲冷哼從身側響起,我...
    開封第一講書人閱讀 42,554評論 0 289
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后,有當地人在樹林里發現了一具尸體,經...
    沈念sama閱讀 49,106評論 1 335
  • 正文 獨居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內容為張勛視角 年9月15日...
    茶點故事閱讀 40,918評論 3 356
  • 正文 我和宋清朗相戀三年,在試婚紗的時候發現自己被綠了。 大學時的朋友給我發了我未婚夫和他白月光在一起吃飯的照片。...
    茶點故事閱讀 43,093評論 1 371
  • 序言:一個原本活蹦亂跳的男人離奇死亡,死狀恐怖,靈堂內的尸體忽然破棺而出,到底是詐尸還是另有隱情,我是刑警寧澤,帶...
    沈念sama閱讀 38,648評論 5 362
  • 正文 年R本政府宣布,位于F島的核電站,受9級特大地震影響,放射性物質發生泄漏。R本人自食惡果不足惜,卻給世界環境...
    茶點故事閱讀 44,342評論 3 347
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧,春花似錦、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 34,755評論 0 28
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至,卻和暖如春,著一層夾襖步出監牢的瞬間,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 36,009評論 1 289
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留,地道東北人。 一個月前我還...
    沈念sama閱讀 51,839評論 3 395
  • 正文 我出身青樓,卻偏偏與公主長得像,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個殘疾皇子,可洞房花燭夜當晚...
    茶點故事閱讀 48,107評論 2 375

推薦閱讀更多精彩內容