以前上傳圖片都是直接將圖片轉化爲io流傳給服務器,沒有用框架傳圖片。java
最近作項目,打算換個方法上傳圖片。服務器
Android發展到如今,Okhttp顯得愈來愈重要,因此,此次我選擇用Okhttp上傳圖片。app
Okhttp目前已經更新到Okhttp3版本了,用法跟以前相比,也有一些差異。在網上找了不少資料,框架
並和java後臺同事反覆調試,終於成功上傳多張圖片,同時傳遞一些鍵值對參數。ide
如下是我對該過程的封裝:post
private static final MediaType MEDIA_TYPE_PNG = MediaType.parse("image/png"); /** * 上傳多張圖片及參數 * @param reqUrl URL地址 * @param params 參數 * @param pic_key 上傳圖片的關鍵字 * @param paths 圖片路徑 */ public Observable<String> sendMultipart(String reqUrl,Map<String, String> params,String pic_key, List<File> files){ return Observable.create(new Observable.OnSubscribe<String>(){ @Override public void call(Subscriber<? super String> subscriber) { MultipartBody.Builder multipartBodyBuilder = new MultipartBody.Builder(); multipartBodyBuilder.setType(MultipartBody.FORM); //遍歷map中全部參數到builder if (params != null){ for (String key : params.keySet()) { multipartBodyBuilder.addFormDataPart(key, params.get(key)); } } //遍歷paths中全部圖片絕對路徑到builder,並約定key如「upload」做爲後臺接受多張圖片的key if (files != null){ for (File file : files) { multipartBodyBuilder.addFormDataPart(pic_key, file.getName(), RequestBody.create(MEDIA_TYPE_PNG, file)); } } //構建請求體 RequestBody requestBody = multipartBodyBuilder.build(); Request.Builder RequestBuilder = new Request.Builder(); RequestBuilder.url(reqUrl);// 添加URL地址 RequestBuilder.post(requestBody); Request request = RequestBuilder.build(); mOkHttpClient.newCall(request).enqueue(new Callback() { @Override public void onFailure(Call call, IOException e) { subscriber.onError(e); subscriber.onCompleted(); call.cancel(); } @Override public void onResponse(Call call, Response response) throws IOException { String str = response.body().string(); subscriber.onNext(str); subscriber.onCompleted(); call.cancel(); } }); } }); }
在UI界面的調用:ui
OkHttp3Utils.getInstance().sendMultipart(Constants.URL.URL_ADD_NOTICE, mMap, "appendix", mImageList) .observeOn(AndroidSchedulers.mainThread()) .subscribeOn(Schedulers.newThread()) .subscribe(new Subscriber<String>() { @Override public void onCompleted() { } @Override public void onError(Throwable throwable) { LogUtil.i(TAG, "throwable:" + throwable.toString()); } @Override public void onNext(String s) { LogUtil.i(TAG, "s:" + s); } });
調試過程當中,有一次將url
multipartBodyBuilder.addFormDataPart(pic_key, file.getName(), RequestBody.create(MEDIA_TYPE_PNG, file));
寫成了
multipartBodyBuilder.addFormDataPart(pic_key, null, RequestBody.create(MEDIA_TYPE_PNG, file));致使後臺沒法用常規方法獲取圖片(雖然斷點調試時也能看到圖片數據),這點須要注意。最後:很是感謝同事的幫助!贈人玫瑰,手有餘香~