1. 程式人生 > >Android Retrofit 2.0框架上傳圖片解決方案(一張與多張的處理)

Android Retrofit 2.0框架上傳圖片解決方案(一張與多張的處理)

1.單張圖片的上傳

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

2.多張圖片的上傳

 /**
         * 上傳三張圖片
         * @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);

注意:目前是提供傳3張,要想多上傳目前我發現的方法就是想要多傳一張,就多增加一個引數
@Part(“file\”; filename=\”image.png\”“)RequestBody imgs,以此類推。

大家看到上面覺得寫法很漏,但是用於能力有限,只能想到這樣。用Java中的可變引數解決之後,就只能傳一張。不能多張。

 @Multipart
        @POST("/upload")
        Call<String> uploadImage(@Part("fileName") String description,
                                 @Part("file\"; filename=\"image.png\"")RequestBody ...imgs);

呼叫:

 Call<String> call = apiManager.uploadImage( m[0],requestBody1,requestBody2,null);

這樣寫看上去很是高階,不幸的是只能傳一張

3.最後是實現過程
3.1建立FileUploadService介面

public interface FileUploadService {
    /**
     * 上傳一張圖片
     * @param description
     * @param imgs
     * @return
     */
    @Multipart
    @POST("/upload")
    Call<String> uploadImage(@Part("fileName") String description,
                             @Part("file\"; 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);
}

3.2建立Retrofit物件

 private static final Retrofit sRetrofit = new Retrofit .Builder()
            .baseUrl(ENDPOINT)
            .addConverterFactory(GsonConverterFactory.create())
//            .addCallAdapterFactory(RxJavaCallAdapterFactory.create()) // 使用RxJava作為回調適配器
            .build();

    private static final FileUploadService apiManager = sRetrofit.create(FileUploadService.class);

3.3呼叫上傳的方法

public static void upload(String path){

    String descriptionString = "hello, this is description speaking";

    String[] m = new String[2];
    m[0]= "share.png";
    m[1]=  "Screenshot_20160128-140709.png";
    File[]  ssssss= new  File[2];
    File file1 = new File("/storage/emulated/0/sc/share.png");
    File file = new File("/storage/emulated/0/Pictures/ScreenShots/Screenshot_20160128-140709.png");
    ssssss[0]=file;
    ssssss[0]=file1;
    RequestBody requestBody[] = new RequestBody[3];
    RequestBody requestBody1 =
            RequestBody.create(MediaType.parse("multipart/form-data"), file);
    RequestBody requestBody2 =
            RequestBody.create(MediaType.parse("multipart/form-data"), file1);
    requestBody[0]=requestBody1;
    requestBody[1]=requestBody2;
    Call<String> call = apiManager.uploadImage( m[0],requestBody1,requestBody2,null);
    call.enqueue(new Callback<String>() {
        @Override
        public void onResponse(Response<String> response, Retrofit retrofit) {
            Log.v("Upload", response.message());
            Log.v("Upload", "success");
        }

        @Override
        public void onFailure(Throwable t) {
            Log.e("Upload", t.toString());
        }
    });

}

4.伺服器段程式碼:
伺服器用的是struts接收:

@Controller
public class GetToken extends  ActionSupport {

/**
     * 
     */
    private static final long serialVersionUID = 1L;
    private File[] file;
    private String[] fileName;
    public File[] getFile() {
        return file;
    }
    public void setFile(File[] file) {
        this.file = file;
    }
    public String[] getFileName() {
        return fileName;
    }
    public void setFileName(String[] fileName) {
        this.fileName = fileName;
    }

    @Action("/upload")
    public void login()  {
        System.out.println("------"+Arrays.toString(file));
        System.out.println("------"+Arrays.toString(fileName));
    }



}

上傳結果:

——[\tmp\upload__4348b3f0_1528c3d9735__8000_00000038.tmp,\tmp\upload__4348b3f0_1528c3d9735__8000_00000040.tmp]
——[“share.png”]
2016-1-29 16:59:04 com.opensymphony.xwork2.util.logging.commons.CommonsLogger info
資訊: Removing file file \tmp\upload__4348b3f0_1528c3d9735__8000_00000038.tmp
2016-1-29 16:59:04 com.opensymphony.xwork2.util.logging.commons.CommonsLogger info
資訊: Removing file file \tmp\upload__4348b3f0_1528c3d9735__8000_00000040.tmp

多圖上傳的一種簡單寫法:

    public static void uploadMany(ArrayList<String> paths,String desp){
        Map<String,RequestBody> photos = new HashMap<>();
        if (paths.size()>0) {
            for (int i=0;i<paths.size();i++) {
                photos.put("photos\"; filename=\"icon.png",  RequestBody.create(MediaType.parse("multipart/form-data"), new File(paths.get(i))));
            }
        }
        Call<String> stringCall = apiManager.uploadImage(desp, photos);
        stringCall.enqueue(new Callback<String>() {
            @Override
            public void onResponse(Call<String> call, Response<String> response) {
                Log.d(TAG, "onResponse() called with: " + "call = [" + call + "], response = [" + response + "]");
            }

            @Override
            public void onFailure(Call<String> call, Throwable t) {
                Log.d(TAG, "onFailure() called with: " + "call = [" + call + "], t = [" + t + "]");
            }
        });
    }