Retrofit學(xué)習(xí)(五)-文件上傳

Retrofit學(xué)習(xí)(五)-文件上傳

Retrofit學(xué)習(xí)(一)-集成
http://www.itdecent.cn/p/86e5cddcc753
Retrofit學(xué)習(xí)(二)-get請(qǐng)求
http://www.itdecent.cn/p/cdde02a0777c
Retrofit學(xué)習(xí)(三)-普通post請(qǐng)求
http://www.itdecent.cn/p/7f252d10fd41
Retrofit學(xué)習(xí)(四)-下載文件
http://www.itdecent.cn/p/f61645a770ae
Retrofit學(xué)習(xí)(五)-文件上傳
http://www.itdecent.cn/p/ca0cb8640c8f

單個(gè)文件上傳 @Multipart @Part

  • 接口

    @Multipart
    @POST("user/imgUpLoad")
//    Call<String> uploadOne(@Part("sign") String sign,@Part("appKey") String appKey,@Part("osName") String osName,@Part("memberNo") String memberNo, @Part  MultipartBody.Part file);
//    Call<String> uploadOne(@PartMap Map<String,String> params, @Part  MultipartBody.Part file);

//    Call<String> uploadOne(@Query("sign") String sign, @Query("appKey") String appKey, @Query("osName") String osName, @Query("memberNo") String memberNo, @Part  MultipartBody.Part file);
    Call<String> uploadOne(@QueryMap Map<String,String> params, @Part  MultipartBody.Part file);

需要添加@Multipart表示支持文件上傳的表單,Content-Type: multipart/form-data
以上4種寫(xiě)法都可以
普通參數(shù)@Query,@QueryMap
或者也@Part,這樣

文件要使用
@Part MultipartBody.Part file

  • 實(shí)現(xiàn)

        String path = "/storage/emulated/0/Pictures/1477553156332.jpg";
        File file = new File(path);

        /**
         * 創(chuàng)建請(qǐng)求體,內(nèi)容是文件
         */
        RequestBody requestFile = RequestBody.create(MediaType.parse("multipart/form-data"), file);
//        final RequestBody requestFile = RequestBody.create(MediaType.parse("image/*"), file);

        /**
         * 創(chuàng)建多部分拿上面的請(qǐng)求體做參數(shù)
         * img 是上傳是的參數(shù)key,根據(jù)需要更改為自己的
         */
        MultipartBody.Part body =
                MultipartBody.Part.createFormData("img", file.getName(), requestFile);

        Map<String,String> params = new HashMap<>();
        params.put("sign", SIGN);
        params.put("appKey", APP_KEY);
        params.put("osName", OS_NAME);
        params.put("memberNo", "13410111258");

        /**
         * 初始化
         */
        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(BASE_URL)
                .addConverterFactory(ScalarsConverterFactory.create())
                .addConverterFactory(GsonConverterFactory.create())
                .build();

        UploadService uploadService = retrofit.create(UploadService.class);
        Call<String> call  = uploadService.uploadOne(params,body);
       // Call<String> call  = uploadService.uploadOne(SIGN,APP_KEY,OS_NAME,"13410111258",body);
        call.enqueue(new Callback<String>() {
            @Override
            public void onResponse(Call<String> call, Response<String> response) {
                L.d("vivi",response.message()+"    "+response.body());
            }

            @Override
            public void onFailure(Call<String> call, Throwable t) {
                t.printStackTrace();
L.d("vivi",t.getMessage());
            }
        });

其中創(chuàng)建Part部分為重要

 String path = "/storage/emulated/0/Pictures/1477553156332.jpg";
        File file = new File(path);

        /**
         * 創(chuàng)建請(qǐng)求體,內(nèi)容是文件
         */
 RequestBody requestFile = RequestBody.create(MediaType.parse("multipart/form-data"), file);
//        final RequestBody requestFile = RequestBody.create(MediaType.parse("image/*"), file);

        /**
         * 創(chuàng)建多部分拿上面的請(qǐng)求體做參數(shù)
         * img 是上傳是的參數(shù)key,根據(jù)需要更改為自己的
         */
        MultipartBody.Part body =
                MultipartBody.Part.createFormData("img", file.getName(), requestFile);

結(jié)果

OK    {"code":"M100001","msg":"成功","info":{"successMessage":"更改成功","memberHeadImg":"http://10.18.200.24:8080/image/cd-img/20161027183654155618134101112581.jpg"},"sign":""}
  • 再來(lái)一個(gè) 單個(gè)文件上傳
    @Multipart
    @POST("file//upload")
    Call<String> upload2(@Part   MultipartBody.Part file);

  • 實(shí)現(xiàn)
 /**
     * 單個(gè) 文件上傳
     * <p>
     * /storage/emulated/0/Pictures/1477553156332.jpg
     * /storage/emulated/0/Pictures/1474366085035.jpg
     * /storage/emulated/0/Pictures/1474522550302.jpg
     * /storage/emulated/0/Pictures/1474423699408.jpg
     * /storage/emulated/0/Pictures/1477553128722.jpg
     * /storage/emulated/0/Pictures/1474365776853.jpg
     */
    private void uploadOne2() {

        String baseUrl = "http://10.18.200.140:8080/hellosp/";

        Retrofit retrofit = new Retrofit.Builder().baseUrl(baseUrl).addConverterFactory(ScalarsConverterFactory.create()).addConverterFactory(GsonConverterFactory.create()).build();

        UploadService uploadService = retrofit.create(UploadService.class);

        String path = "/storage/emulated/0/Pictures/1477553156332.jpg";

        File file = new File(path);

        RequestBody requestBody = RequestBody.create(MediaType.parse("multipart/form-data"), file);

        /**
         * 創(chuàng)建多部分拿上面的請(qǐng)求體做參數(shù)
         * img 是上傳是的參數(shù)key,根據(jù)需要更改為自己的
         */
        MultipartBody.Part body = MultipartBody.Part.createFormData("file", file.getName(), requestBody);

        Call<String> call = uploadService.upload2(body);

        call.enqueue(new Callback<String>() {
            @Override
            public void onResponse(Call<String> call, Response<String> response) {
                L.d("vivi", response.message() + "    " + response.body());
            }

            @Override
            public void onFailure(Call<String> call, Throwable t) {
                t.printStackTrace();
                L.d("vivi", t.getMessage());
            }
        });

    }

  • 也可以另一種寫(xiě)法
 /**
     * 單個(gè) 文件上傳
     * /storage/emulated/0/Pictures/1477553156332.jpg
     * /storage/emulated/0/Pictures/1474366085035.jpg
     * /storage/emulated/0/Pictures/1474522550302.jpg
     * /storage/emulated/0/Pictures/1474423699408.jpg
     * /storage/emulated/0/Pictures/1477553128722.jpg
     * /storage/emulated/0/Pictures/1474365776853.jpg
     */
    private void uploadOne3() {

        String baseUrl = "http://10.18.200.140:8080/hellosp/";

        Retrofit retrofit = new Retrofit.Builder().baseUrl(baseUrl).addConverterFactory(ScalarsConverterFactory.create()).addConverterFactory(GsonConverterFactory.create()).build();

        UploadService uploadService = retrofit.create(UploadService.class);

        String path = "/storage/emulated/0/Pictures/1477553156332.jpg";

        File file = new File(path);

        RequestBody requestBody = RequestBody.create(MediaType.parse("multipart/form-data"), file);
        Map<String, RequestBody> params = new HashMap<>();

        params.put("file\"; filename=\"" + file.getName() + "", requestBody);

        Call<String> call = uploadService.upload3(params);

        call.enqueue(new Callback<String>() {
            @Override
            public void onResponse(Call<String> call, Response<String> response) {
                L.d("vivi", response.message() + "    " + response.body());
            }

            @Override
            public void onFailure(Call<String> call, Throwable t) {
                t.printStackTrace();
                L.d("vivi", t.getMessage());
            }
        });

    }

看到不同了嗎?參數(shù)的拼接不同
第一種

     /**
         * 創(chuàng)建請(qǐng)求體,內(nèi)容是文件
         */
 RequestBody requestFile = RequestBody.create(MediaType.parse("multipart/form-data"), file);
//        final RequestBody requestFile = RequestBody.create(MediaType.parse("image/*"), file);

        /**
         * 創(chuàng)建多部分拿上面的請(qǐng)求體做參數(shù)
         * img 是上傳是的參數(shù)key,根據(jù)需要更改為自己的
         */
        MultipartBody.Part body =
                MultipartBody.Part.createFormData("img", file.getName(), requestFile);

第二種

 RequestBody requestBody = RequestBody.create(MediaType.parse("multipart/form-data"), file);
        Map<String, RequestBody> params = new HashMap<>();

        params.put("file\"; filename=\"" + file.getName() + "", requestBody);

第二種比較適合多文件上傳

file 是參數(shù)

多個(gè)文件上傳

  • 接口

    @Multipart
    @POST("file//upload")
    Call<String> upload22(@PartMap   Map<String,RequestBody> params);
  • 實(shí)現(xiàn)
 /**
     * 文件上傳
     * <p>
     * /storage/emulated/0/Pictures/1477553156332.jpg
     * /storage/emulated/0/Pictures/1474366085035.jpg
     * /storage/emulated/0/Pictures/1474522550302.jpg
     * /storage/emulated/0/Pictures/1474423699408.jpg
     * /storage/emulated/0/Pictures/1477553128722.jpg
     * /storage/emulated/0/Pictures/1474365776853.jpg
     */
    private void uploadOne22() {

        String baseUrl = "http://10.18.200.140:8080/hellosp/";

        Retrofit retrofit = new Retrofit.Builder().baseUrl(baseUrl).addConverterFactory(ScalarsConverterFactory.create()).addConverterFactory(GsonConverterFactory.create()).build();

        UploadService uploadService = retrofit.create(UploadService.class);

        String path  = "/storage/emulated/0/Pictures/1477553156332.jpg";
        String path2 = "/storage/emulated/0/Pictures/1474366085035.jpg";
        // String path3 = "/storage/emulated/0/Pictures/1474522550302.jpg";
        String path4 = "/storage/emulated/0/Pictures/1474423699408.jpg";
        String path5 = "/storage/emulated/0/Pictures/1477553128722.jpg";
        String path6 = "/storage/emulated/0/Pictures/1474365776853.jpg";

        File file  = new File(path);
        File file2 = new File(path2);
        // File file3 = new File(path3);
        File file4 = new File(path4);
        File file5 = new File(path5);
        File file6 = new File(path6);

        File[] files = new File[]{file, file2, file4, file5, file6};

        Map<String, RequestBody> params = new HashMap<>();

        for(int i = 0; i < files.length; i++) {
            RequestBody requestBody = RequestBody.create(MediaType.parse("multipart/form-data"), files[i]);
            params.put("file\"; filename=\"" + files[i].getName() + "", requestBody);
        }

      /*  *//**
         * 創(chuàng)建多部分拿上面的請(qǐng)求體做參數(shù)
         * img 是上傳是的參數(shù)key,根據(jù)需要更改為自己的
         *//*
        MultipartBody.Part body =
                MultipartBody.Part.createFormData("file", file.getName(), requestBody);
*/

        Call<String> call = uploadService.upload22(params);

        call.enqueue(new Callback<String>() {
            @Override
            public void onResponse(Call<String> call, Response<String> response) {
                L.d("vivi", response.message() + "    " + response.body());
            }

            @Override
            public void onFailure(Call<String> call, Throwable t) {
                t.printStackTrace();
                L.d("vivi", t.getMessage());
            }
        });

    }

基本的應(yīng)用就算完成了
源碼:
https://github.com/ln0491/RetrofitDemo2
上傳服務(wù)器代碼
https://github.com/ln0491/hellosp
半吊子springMVC寫(xiě)的有需要的就用吧,上傳路徑自己改下
在UploadController-addUser方法

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • Android 自定義View的各種姿勢(shì)1 Activity的顯示之ViewRootImpl詳解 Activity...
    passiontim閱讀 178,995評(píng)論 25 709
  • 整體Retrofit內(nèi)容如下: 1、Retrofit解析1之前哨站——理解RESTful2、Retrofit解析2...
    隔壁老李頭閱讀 15,388評(píng)論 4 39
  • 前些日子從@張?chǎng)涡裎⒉┨幍靡环萃扑](Front-end-tutorial),號(hào)稱最全的資源教程-前端涉及的所有知識(shí)...
    谷子多閱讀 4,489評(píng)論 0 44
  • 感謝痛苦,它讓我不斷成長(zhǎng),并且它的好處還在于,不被別人嫉妒。
    七色黑白閱讀 306評(píng)論 0 0
  • 用長(zhǎng)焦鏡頭在運(yùn)河公園所拍,三角形的這個(gè)風(fēng)箏是一位老者在放,從中午一直放到晚上8點(diǎn),天色一黑風(fēng)箏上的燈會(huì)亮起來(lái),可...
    姑蘇阿杰閱讀 440評(píng)論 0 1

友情鏈接更多精彩內(nèi)容