Retrofit(重构——上传文件)

下载文件告一段落,这篇文章讲解利用retrofit上传文件。
老规矩,贴代码。

        String headerPath = "/sdcard/test.jpg";
        File f = new File(headerPath);
        Bitmap bitmap = BitmapFactory.decodeFile(headerPath);
        int width = bitmap.getWidth();
        int height = bitmap.getHeight();
        long fsize = getFileSizes(f);
        UpXlUpLoadFile upXlUpLoadFile = new UpXlUpLoadFile();
        upXlUpLoadFile.setK("xxxxx");
        upXlUpLoadFile.setU("xxxxx");
        upXlUpLoadFile.setFwidth(width + "");
        upXlUpLoadFile.setFheight(height + "");
        upXlUpLoadFile.setFsize(fsize + "");
        upXlUpLoadFile.setFtype("photo");
        upXlUpLoadFile.setCandel("0");
        upXlUpLoadFile.setUpend("1");
        upXlUpLoadFile.setExt("jpg");
         Gson gson = new Gson();
        String str = gson.toJson(upXlUpLoadFile);
        String baseStr = Base64.encodeToString(str.getBytes(),
                Base64.DEFAULT);

        RequestBody requestBody = RequestBody.create(MediaType.parse("text/plain"), baseStr);
        RequestBody requestBodyFile = RequestBody.create(MediaType.parse("application/octet-stream"), f);
        Map<String, RequestBody> params = new HashMap<>();
        params.put("p", requestBody);
        params.put("f\"; filename=\"test.jpg", requestBodyFile); //此处是关键(对应服务端的p和f多块参数的name,[不明白的戳](http://my.oschina.net/cnlw/blog/168466?fromerr=aQL9sTI2))
        Subscription subscription = clientApi.upXlFile(params)
                .compose(SchedulersCompat.<Response>applyIoSchedulers())
                .subscribe(new Subscriber<Response>() {
                    @Override
                    public void onCompleted() {
                        topbarTrans.setClickable(true);
                        transSwipe.setRefreshing(false);
                        topbarTrans.stopRotate();
                        hideLoadingDialog();
                    }

                    @Override
                    public void onError(Throwable e) {
                        showToast("更新失败");
                        Log.e("yan", e.toString());
                    }

                    @Override
                    public void onNext(Response response) {
                    }
                });
        mCompositeSubscription.add(subscription);

api

    /*上传图片*/
    @Multipart @POST("/xl/file_upload") Observable<Response> upXlFile(@PartMap Map<String ,RequestBody> params);

ok,retrofit部分结束,如有问题,日后再行记录。

你可能感兴趣的:(post,上传,文件,retrofit)