- 由于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)
到這里,我們的批量上傳就結束了,如果各位朋友有什么更好的辦法,請教教我。。。
### 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)

[博客看不到?點我看圖](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)
#### 3.4 批量上傳的進度監聽
我們知道了如何監聽單個文件的上傳進度,多個文件,恩,就不說了啊,(添加多個轉換器嘍)。
### 4. 總結
Retrofit很強大 很強大,有的同學想讓我配合上Rxjava寫,哎,朋友,給個面子啊,好歹把我第一篇基礎用法看看哪。還剩下許多許多的功能沒介紹,看朋友們有什么需求了,可以給我留言,完了一起研究啊。