天天看點

Retrofit2.0進行圖檔上傳(後端Spring MVC)

你該繞過的坑

Android端

  1. 用版本不低于2.0.1的庫,不然在進行上傳時會報類型轉換錯誤
  2. 轉換工廠庫版本也不應低于2.0.1的

build.gradle依賴

compile ‘com.squareup.retrofit2:retrofit:2.0.1’

compile ‘com.squareup.retrofit2:converter-gson:2.0.1’

Retrofit初始化

Retrofit retrofit = new Retrofit.Builder()
                .addConverterFactory(GsonConverterFactory.create())
                //基礎位址,這裡我以本地測試進行
                .baseUrl("http://192.168.30.149:8080")
                .build();
           

接口編寫

  • 需要上傳其他參數,可在方法裡使用@Part進行添加 。實際開發中,我們上傳圖檔需要與背景使用者表進行關聯,建議講token放于請求頭。
  • 當上傳因為其他原因不成功時,檔案名在背景配置的檔案夾裡會以多一個引号結尾
  • 下面的‘pic’為與背景約定的檔案參數key
public interface FileUploadService {
  /**
   * 上傳一張圖檔
   * @param description
   * @param imgs
   * @return
   */
  @Multipart
  @POST("/app/person/uploadpic.htm")
  Call<Result> uploadImage(@Part("filename") String description,
                                 @Part("pic\"; filename=\"image.png") RequestBody imgs);

  /**
   * 上傳三張圖檔
   * @param description
   * @param imgs
   * @param imgs1
   * @param imgs3
   * @return
   */
  @Multipart
  @POST("/upload")
  Call<String> uploadImage(@Part("fileName") String description,
         @Part("file\"; filename=\"image.png\"")RequestBody imgs,
         @Part("file\"; filename=\"image.png\"")RequestBody imgs1,
         @Part("file\"; filename=\"image.png\"")RequestBody imgs3);
 }
           

使用

File file = new File("/mnt/sdcard/Download/29381f30e924b899cf2bfd036b061d950a7bf6f2.jpg");

//用RequestBody包裹檔案,application/octet-stream為檔案類型,這裡為二進制流,不知道檔案類型時所用
        RequestBody requestBody =
                RequestBody.create(MediaType.parse("application/octet-stream"), file);

        FileUploadService apiManager = retrofit.create(FileUploadService.class);
        Call<Result> call = apiManager.uploadImage("img",requestBody);

        call.enqueue(new Callback<Result>() {
            @Override
            public void onResponse(Call<Result> call, Response<Result> response) {
                    Log.d("=======",response.body().getUrl());

            }

            @Override
            public void onFailure(Call<Result> call, Throwable t) {
                    Log.d("======",t.toString());
            }
        });
           

Spring MVC

檔案上傳配置mod_spring_view.xml

<!-- 檔案上傳 --> 
    <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"
        p:defaultEncoding="UTF-8"
        p:resolveLazily="true"
        p:maxUploadSize="52428800"
        p:uploadTempDir="upload/temp"/>
           

Controller層

@RequestMapping(value = "uploadPic.htm")
    public String uploadPic(Model model, MultipartFile pic){
        Result result = new Result();
        //...此處進行存儲,每個人寫法不一樣
        return "jsonview";
    }
           

繼續閱讀