下載進度的在之前的文章中實現(xiàn)過:
Android的Splash啟動圖的兩種動態(tài)切換方式
根據(jù)服務(wù)器的數(shù)據(jù)聲明上傳文件的方法
@Multipart
@POST("upload")
Observable<UploadImgBean> uploadHeadPic(@Part MultipartBody.Part files);
借助okhttp的RequestBody
我們構(gòu)造一個FileRequestBody
繼承RequestBody
public class FileRequestBody extends RequestBody {
private RequestBody mRequestBody;
private LoadingListener mLoadingListener;
private long mContentLength;
public FileRequestBody(RequestBody requestBody, LoadingListener loadingListener) {
mRequestBody = requestBody;
mLoadingListener = loadingListener;
}
//文件的總長度
@Override
public long contentLength() {
try {
if (mContentLength == 0)
mContentLength = mRequestBody.contentLength();
return mContentLength;
} catch (IOException e) {
e.printStackTrace();
}
return -1;
}
@Override
public MediaType contentType() {
return mRequestBody.contentType();
}
@Override
public void writeTo(BufferedSink sink) throws IOException {
ByteSink byteSink = new ByteSink(sink);
BufferedSink mBufferedSink = Okio.buffer(byteSink);
mRequestBody.writeTo(mBufferedSink);
mBufferedSink.flush();
}
private final class ByteSink extends ForwardingSink {
//已經(jīng)上傳的長度
private long mByteLength = 0L;
ByteSink(Sink delegate) {
super(delegate);
}
@Override
public void write(Buffer source, long byteCount) throws IOException {
super.write(source, byteCount);
mByteLength += byteCount;
mLoadingListener.onProgress(mByteLength, contentLength());
}
}
public interface LoadingListener {
void onProgress(long currentLength, long contentLength);
}
}
實現(xiàn)上傳
RequestBody requestFile =
RequestBody.create(MediaType.parse("multipart/form-data"), file);
FileRequestBody fileRequestBody = new FileRequestBody(requestFile, new FileRequestBody.LoadingListener() {
@Override
public void onProgress(long currentLength, long contentLength) {
//獲取上傳的比例
Log.d("Tag---", currentLength + "/" + contentLength);
}
});
//files是與服務(wù)器對應(yīng)的key
MultipartBody.Part body =
MultipartBody.Part.createFormData("files", file.getName(), fileRequestBody);
RetrofitHelper.userApi().uploadHeadPic(body).subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new Action1<UploadImgBean>() {
@Override
public void call(UploadImgBean uploadImgBean) {
//上傳成功
}
}, new Action1<Throwable>() {
@Override
public void call(Throwable throwable) {
//上傳失敗
}
});