
引言
利用Retorfit和RxJava的結(jié)合實(shí)現(xiàn)將圖片上傳到服務(wù)器,并且獲取圖片上傳的的進(jìn)度。
具體實(shí)現(xiàn)
- 首先定義網(wǎng)絡(luò)請求接口
//上傳圖片
@Multipart
@POST("everecords")
Observable<CommonResult> uploadPicture(@Part("teacher_id") long teacher_id,
@Part("event_id") long event_id,
@Part("child_ids") String child_ids,
@Part("eve_tags") String eve_tags,
@PartMap Map<String, RequestBody> params);
我們利用@Multipart注解,并且上傳圖片時(shí)也可以利用@Part注解傳遞一些其他參數(shù),注解@PartMap我們可以一次上傳多張圖片。
- 核心代碼
Map<String, RequestBody> bodyMap = new HashMap<>();
File file = new File(path);
bodyMap.put("assets" + 0 + "\"; filename=\"" + file.getName(), new ProgressRequestBody(file, new ProgressRequestBody.UploadCallbacks() {
@Override
public void onProgressUpdate(int percentage,long id) {
Logger.d("圖片"+pictureId+"的上傳進(jìn)度:"+percentage);
}
}));
//提交到服務(wù)器
RequestManager.retrofit()
.create(RequestAPI.class)
.uploadPicture(teacherId, eventId, childIds, commentIds, bodyMap)
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new Observer<CommonResult>() {
@Override
public void onSubscribe(Disposable d) {
}
@Override
public void onNext(CommonResult value) {
Logger.d("請求成功----->圖片上傳");
//所有的圖片上傳成功后進(jìn)行相應(yīng)的處理
}
@Override
public void onError(Throwable e) {
Logger.e("請求失敗---->圖片上傳:" + e.getMessage());
}
@Override
public void onComplete() {
}
});
- 下面時(shí)ProgressRequestBody類,構(gòu)造RequestBody時(shí)用到的
public class ProgressRequestBody extends RequestBody {
private File mFile;
private String mPath;
private UploadCallbacks mListener;
private long id;
private static final int DEFAULT_BUFFER_SIZE = 2048;
public interface UploadCallbacks {
void onProgressUpdate(int percentage,long id);
}
public ProgressRequestBody(long id,final File file, final UploadCallbacks listener) {
this.id = id;
mFile = file;
mListener = listener;
}
public ProgressRequestBody(final File file, final UploadCallbacks listener) {
this.id = id;
mFile = file;
mListener = listener;
}
@Override
public MediaType contentType() {
// i want to upload only images
return MediaType.parse("image/*");
}
@Override
public long contentLength() throws IOException {
return mFile.length();
}
@Override
public void writeTo(BufferedSink sink) throws IOException {
long fileLength = mFile.length();
byte[] buffer = new byte[DEFAULT_BUFFER_SIZE];
FileInputStream in = new FileInputStream(mFile);
long uploaded = 0;
try {
int read;
Handler handler = new Handler(Looper.getMainLooper());
while ((read = in.read(buffer)) != -1) {
uploaded += read;
sink.write(buffer, 0, read);
// update progress on UI thread
handler.post(new ProgressUpdater(uploaded, fileLength));
}
} finally {
in.close();
}
}
private class ProgressUpdater implements Runnable {
private long mUploaded;
private long mTotal;
public ProgressUpdater(long uploaded, long total) {
mUploaded = uploaded;
mTotal = total;
}
@Override
public void run() {
mListener.onProgressUpdate((int) (100 * mUploaded / mTotal),id);
}
}
}
該類是獲取圖片上傳進(jìn)度的核心類。
文章寫的非常簡潔,有問題的大家可以留言探討。