天天看點

Android Retrofit 2.0架構上傳圖檔解決方案(一張與多張的處理) 标題: Android Retrofit 2.0架構上傳圖檔解決方案(一張與多張的處理)

版權聲明:本文為部落客原創文章,未經部落客允許不得轉載。 https://blog.csdn.net/u010046908/article/details/50608182

 标題: 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

資訊: Removing file file \tmp\upload__4348b3f0_1528c3d9735__8000_00000040.tmp

  總共就這些吧。有問題大家在下面說。QQ1561281670

代碼下載下傳位址

追加:

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

</pre><pre name="code" class="java">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"+i+"\"; 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 + "]");
            }
        });
    }           

這樣洗是不是比上面的好多了。如果再有什麼好的寫法,請提出來。我在改進

繼續閱讀