Android Retrofit 2.0框架上传图片解决方案(一张与多张的处理)


 标题: Android Retrofit 2.0框架上传图片解决方案(一张与多张的处理)

 1.单张图片的上传

   
  1. /** 
  2.          * 上传一张图片 
  3.          * @param description 
  4.          * @param imgs 
  5.          * @return 
  6.          */  
  7.         @Multipart  
  8.         @POST("/upload")  
  9.         Call<String> uploadImage(@Part("fileName") String description,  
  10.                                  @Part("file\"; filename=\"image.png\"")RequestBody imgs);  
/**
         * 上传一张图片
         * @param description
         * @param imgs
         * @return
         */
        @Multipart
        @POST("/upload")
        Call<String> uploadImage(@Part("fileName") String description,
                                 @Part("file\"; filename=\"image.png\"")RequestBody imgs);


  2.多张图片的上传

    
  1. /** 
  2.         * 上传三张图片 
  3.         * @param description 
  4.         * @param imgs 
  5.         * @param imgs1 
  6.         * @param imgs3 
  7.         * @return 
  8.         */  
  9.        @Multipart  
  10.        @POST("/upload")  
  11.        Call<String> uploadImage(@Part("fileName") String description,  
  12.                                 @Part("file\"; filename=\"image.png\"")RequestBody imgs,  
  13.                                 @Part("file\"; filename=\"image.png\"")RequestBody imgs1,  
  14.                                 @Part("file\"; filename=\"image.png\"")RequestBody imgs3);  
 /**
         * 上传三张图片
         * @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中的可变参数解决之后,就只能传一张。不能多张。
  1. @Multipart  
  2.        @POST("/upload")  
  3.        Call<String> uploadImage(@Part("fileName") String description,  
  4.                                 @Part("file\"; filename=\"image.png\"")RequestBody ...imgs);  
 @Multipart
        @POST("/upload")
        Call<String> uploadImage(@Part("fileName") String description,
                                 @Part("file\"; filename=\"image.png\"")RequestBody ...imgs);

     调用:
  1. Call<String> call = apiManager.uploadImage( m[0],requestBody1,requestBody2,null);  
 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接收:
  1. @Controller  
  2. public class GetToken extends  ActionSupport {  
  3.       
  4. /** 
  5.      *  
  6.      */  
  7.     private static final long serialVersionUID = 1L;  
  8.     private File[] file;  
  9.     private String[] fileName;  
  10.     public File[] getFile() {  
  11.         return file;  
  12.     }  
  13.     public void setFile(File[] file) {  
  14.         this.file = file;  
  15.     }  
  16.     public String[] getFileName() {  
  17.         return fileName;  
  18.     }  
  19.     public void setFileName(String[] fileName) {  
  20.         this.fileName = fileName;  
  21.     }  
  22.   
  23.     @Action("/upload")  
  24.     public void login()  {  
  25.         System.out.println("------"+Arrays.toString(file));  
  26.         System.out.println("------"+Arrays.toString(fileName));  
  27.     }  
  28.       
  29.       
  30.       
  31. }  
@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


  总共就这些吧。有问题大家在下面说。QQ1561281670

代码下载地址



追加:

多图上传的一种简单那写法:

  1. </pre><pre name="code" class="java">public static void uploadMany(ArrayList<String> paths,String desp){  
  2.         Map<String,RequestBody> photos = new HashMap<>();  
  3.         if (paths.size()>0) {  
  4.             for (int i=0;i<paths.size();i++) {  
  5.                 photos.put("photos"+i+"\"; filename=\"icon.png",  RequestBody.create(MediaType.parse("multipart/form-data"), new File(paths.get(i))));  
  6.             }  
  7.         }  
  8.         Call<String> stringCall = apiManager.uploadImage(desp, photos);  
  9.         stringCall.enqueue(new Callback<String>() {  
  10.             @Override  
  11.             public void onResponse(Call<String> call, Response<String> response) {  
  12.                 Log.d(TAG, "onResponse() called with: " + "call = [" + call + "], response = [" + response + "]");  
  13.             }  
  14.   
  15.             @Override  
  16.             public void onFailure(Call<String> call, Throwable t) {  
  17.                 Log.d(TAG, "onFailure() called with: " + "call = [" + call + "], t = [" + t + "]");  
  18.             }  
  19.         });  
  20.     }  
</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 + "]");
            }
        });
    }

这样洗是不是比上面的好多了。如果再有什么好的写法,请提出来。我在改进
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值