Retrofit 上传图片(多张)

本文介绍如何通过使用@PartMap注解优化图片上传API,提高上传效率和灵活性。具体步骤包括创建RequestBody实例,配置参数,并通过Retrofit进行调用。

修改interface——ApiUploadImg,使用@PartMap注解:

public interface ApiUploadImg {
   /**图片上传API*/
  /*  @POST("Comm")
    Observable<ResponseApi<UploadImgResponse>> uploadImg(@Body RequestApi RequestApi);*/

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

//    @Multipart
//    @POST("Comm/uploadImg")
//    Observable<ResponseApi<UploadImgResponse>> uploadImg( @Part("description") RequestBody description, @Part MultipartBody.Part file);

//    @Multipart
//    @POST("Comm/uploadImg")
//    Call<UploadImgResponse> uploadImg( @Part("description") RequestBody description, @Part MultipartBody.Part file);

    @Multipart
    @POST("Comm/uploadImg")
    Call<UploadImgResponse> uploadImg(@PartMap Map<String, RequestBody> params);
}
使用:
<pre name="code" class="java">package cn.suanzi.tcwl_manage.utils;

        import android.content.Context;
        import android.util.Log;

        import java.io.File;
        import java.util.HashMap;
        import java.util.List;
        import java.util.Map;

        import cn.suanzi.tc_base.api.RetrofitUtil;
        import cn.suanzi.tcwl_manage.R;
        import cn.suanzi.tcwl_manage.models.enties.response.UploadImgResponse;
        import cn.suanzi.tcwl_manage.models.services.ApiUploadImg;
        import okhttp3.MediaType;
        import okhttp3.RequestBody;
        import retrofit2.Call;
        import retrofit2.Callback;
        import retrofit2.Response;

/**
 * Created by MAOYH on 2016/4/20.
 * 上传图片
 */
public class UploadImgUtil  {
    private static String imgUrl;

    public static String getImgUrl() {
        return imgUrl;
    }

    public static void setImgUrl(String imgUrl) {
        UploadImgUtil.imgUrl = imgUrl;
    }

    public static void upLoadImg(final Context context ,List<String> imgStrs) {
        Map<String, RequestBody> params = new HashMap<>();
        for(String imgStr :imgStrs) {
            File file = new File(imgStr);
            // create RequestBody instance from file
            RequestBody  requestFile = RequestBody.create(MediaType.parse("multipart/form-data"), file);
            //一定要加("AttachmentKey\"; filename=\"" +,不然失败
            params.put("AttachmentKey\"; filename=\"" +file.getName(),requestFile);
        }

        // create upload service client
        ApiUploadImg service = RetrofitUtil.getInstance().getService(ApiUploadImg.class);

        // finally, execute the request
        Call<UploadImgResponse> call = service.uploadImg(params);
        call.enqueue(new Callback<UploadImgResponse>() {
            @Override
            public void onResponse(Call<UploadImgResponse> call, Response<UploadImgResponse> response) {
                if (null != response) {
                    int code = response.body().getCode();
                    imgUrl = response.body().getImgUrl();

                    switch (code) {
                        case 50000:
                            ToastUtil.toast(context, "上传图片成功");
                            break;
                        case 80020:
                            ToastUtil.toast(context, "上传图片失败,图片格式不正确");
                            break;
                        case 80021:
                            ToastUtil.toast(context, "上传图片失败,图片大小不正确");
                            break;
                        case 80022:
                            ToastUtil.toast(context, "上传图片失败,没有上传的图片");
                            break;
                    }
                    Log.e("图片路径", "图片路径:" + imgUrl);


                } else {
                    ToastUtil.toast(context, context.getResources().getString(R.string.server_null));

                }

            }

            @Override
            public void onFailure(Call<UploadImgResponse> call, Throwable e) {
                ToastUtil.toast(context, context.getString(R.string.connect_server_error) + e.getMessage());

            }
        });

    }
}




在Android开发中,结合OkHttp和Retrofit库可以方便地处理HTTP请求,包括文件上传,如照片。以下是使用这两个库上传多张照片的基本步骤: 1. **添加依赖**: 首先,确保在你的`build.gradle`文件中添加了OkHttp和Retrofit的依赖: ```groovy implementation 'com.squareup.okhttp3:okhttp:4.x' implementation 'com.squareup.retrofit2:retrofit:2.x' implementation 'com.squareup.retrofit2:converter-gson:2.x' ``` 可能还需要添加图片处理库(例如Picasso或Glide),用于压缩或适配上传图片。 2. **创建接口和服务**: 创建一个包含文件上传方法的Retrofit接口,假设我们叫它`ImageUploadService`: ```java public interface ImageUploadService { @Multipart Call<ResponseBody> uploadPhotos(@Part("image[]") MultipartBody.Part... parts); } ``` 3. **构造Retrofit实例**: 在需要上传图片的地方,构建一个Retrofit实例并获取到服务: ```java OkHttpClient client = new OkHttpClient(); Retrofit retrofit = new Retrofit.Builder() .baseUrl("your_api_url") .addConverterFactory(GsonConverterFactory.create()) .client(client) .build(); ImageUploadService service = retrofit.create(ImageUploadService.class); ``` 4. **上传照片**: 为了上传多张照片,你需要遍历你的`Bitmap`或`File`数组,并将其转换为`MultipartBody.Part`: ```java List<MultipartBody.Part> imageParts = new ArrayList<>(); for (File file : filesToUpload) { RequestBody requestBody = RequestBody.create(MediaType.parse("image/*"), file); imageParts.add(RequestBody.createFormData("image[]", file.getName(), requestBody)); } Call<ResponseBody> call = service.uploadPhotos(imageParts.toArray(new Part[0])); call.enqueue(new Callback<ResponseBody>() { // Handle success and error cases }); ``` 5. **处理回调**: 当上传完成时,会在`Callback`的`onResponse()`方法中处理服务器响应。你可以在这里检查上传状态,比如响应码和错误信息。 记得替换上述代码中的`your_api_url`为你实际的API地址。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值