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 結果展示
部落格看不到?點我看圖
到這裡,我們的批量上傳就結束了,如果各位朋友有什麼更好的辦法,請教教我。。。
3.上傳進度的監聽
當想到這個問題的時候,完全沒有思路,那就尷尬了。仔細想想,好吧,還是沒有思路,那麼,咱們去看看github上官方給出的幾個類,。就看這個類 就看這個類
恩,我給出2張圖,大家自己觀察下
部落格看不到?點我看圖
部落格看不到?點我看圖
發現沒?轉化器中出現了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上將這個類下載來下。連結地址
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 結果演示
3.4 批量上傳的進度監聽
我們知道了如何監聽單個檔案的上傳進度,多個檔案,恩,就不說了啊,(新增多個轉換器嘍)。
4. 總結
Retrofit很強大 很強大,有的同學想讓我配合上Rxjava寫,哎,朋友,給個面子啊,好歹把我第一篇基礎用法看看哪。還剩下許多許多的功能沒介紹,看朋友們有什麼需求了,可以給我留言,完了一起研究啊。