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阅读 160,165评论 4 364
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 67,720评论 1 298
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 109,849评论 0 244
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 44,245评论 0 213
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 52,596评论 3 288
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 40,747评论 1 222
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 31,977评论 2 315
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 30,708评论 0 204
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 34,448评论 1 246
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 30,657评论 2 249
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 32,141评论 1 261
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 28,493评论 3 258
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 33,153评论 3 238
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 26,108评论 0 8
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,890评论 0 198
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 35,799评论 2 277
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 35,685评论 2 272

推荐阅读更多精彩内容