1. 程式人生 > >使用Retrofit+RxJava上傳檔案

使用Retrofit+RxJava上傳檔案

最近做了一個上傳頭像的demo,下面進行使用和介紹的記錄

我的圖片格式是Bitmap格式,所以這裡要轉換成檔案

//Bitmap轉檔案
    public File getFile(Bitmap bmp) {
        //Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.mipmap.ic_launcher);
        //getApplicationContext 更改為 getContext
        String defaultPath = getApplicationContext().getFilesDir()
                .getAbsolutePath() + "/defaultGoodInfo";
        File file = new File(defaultPath);
        if (!file.exists()) {
            file.mkdirs();
        }
        String defaultImgPath = defaultPath + "/messageImg.jpg";
        file = new File(defaultImgPath);
        try {
            file.createNewFile();
            FileOutputStream fOut = new FileOutputStream(file);
            bmp.compress(Bitmap.CompressFormat.PNG, 20, fOut);
            fOut.flush();
            fOut.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return file;
    }

下面是Retrofit的介面

@Multipart
    @POST("file/upload")
    Observable<NetWork> postUpLodding(@Query("uid") int uid , @Part MultipartBody.Part file);

工具類

public class RetrofitUtil {
    private static volatile RetrofitUtil sRetrofitUtil;
    private final OkHttpClient mHttpClient;

    private RetrofitUtil() {
        mHttpClient = new OkHttpClient.Builder()
                .connectTimeout(10, TimeUnit.SECONDS)
                .readTimeout(10, TimeUnit.SECONDS)
                .writeTimeout(10, TimeUnit.SECONDS)
                .build();
    }

    //例項化
    public static RetrofitUtil getInstance(){
        if(sRetrofitUtil == null){
            synchronized (RetrofitUtil.class){
                if(sRetrofitUtil == null){
                    sRetrofitUtil = new RetrofitUtil();
                }
            }
        }
        return sRetrofitUtil;
    }

    //方法
    public Observable<NetWork> doPost(String url, File file){

        //設定圖片格式
        RequestBody requestFile = RequestBody.create(MediaType.parse("image/jpg"), file);
        //設定一個file檔案
        MultipartBody.Part body = MultipartBody.Part.createFormData("file", file.getName(), requestFile);
        RetrofitServer retrofitServer = new Retrofit.Builder()
                .client(mHttpClient)
                .baseUrl(url)
                .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                .addConverterFactory(GsonConverterFactory.create())
                .build().create(RetrofitServer.class);

        return  retrofitServer.postUpLodding(71,body).subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread());
    }
}

獲取資料的方法,參考即可

//轉成檔案格式
        File file = getFile(bitmap);

        RetrofitUtil instance = RetrofitUtil.getInstance();
        instance.doPost(CantroUrl.BASE_URL, file).subscribe(new Observer<NetWork>() {
            @Override
            public void onSubscribe(Disposable d) {

            }

            @Override
            public void onNext(NetWork s) {
                if("0".equals(s.getCode())){
                    Toast.makeText(MainActivity.this, "頭像上傳成功", Toast.LENGTH_SHORT).show();
                }else{
                    Toast.makeText(MainActivity.this, "上傳失敗", Toast.LENGTH_SHORT).show();
                }
            }

            @Override
            public void onError(Throwable e) {
            }

            @Override
            public void onComplete() {

            }
        });

但是寫完後發現會報一個錯誤

java.net.SocketException: sendto failed: ECONNRESET (Connection reset by peer)

解決,在Activity中的onCreate宣告週期中加入

if (android.os.Build.VERSION.SDK_INT > 9) {
            StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()
                    .permitAll().build();
            StrictMode.setThreadPolicy(policy);
        }