• Retrofit2 上传图片等文件


    普通写法:

    //创建表单的普通字段
    public
    static RequestBody createFormBody(String content) {   RequestBody body = RequestBody.create(MediaType.parse("multipart/form-data"), content);   return body; }
    //创建Multipart, fieldName为表单字段名
    public static MultipartBody.Part createFilePart(String fieldName, File file) {
      RequestBody requestFile = RequestBody.create(MediaType.parse("application/otcet-stream"), file);
      MultipartBody.Part body = MultipartBody.Part.createFormData(fieldName, file.getName(), requestFile);
       return body;
    }
    //Service方法, 普通form表单使用RequestBody, 并且@Part注解要写表单字段名
    //文件用MultipartBody.Part
    @Multipart
    @POST(API.VIDEO_MODULE_UPLOAD_VIDEO)
    Call<Object> uploadImage(@Part MultipartBody.Part imagePicFile,
                             @Part MultipartBody.Part videoFile,
                             @Part("videoDescription") RequestBody desc,
                             @Part("videoPicWidth") RequestBody videoPicWidth,
                             @Part("videoPicHeight") RequestBody videoPicHeight);
       
    //上传
    getService(VideoService.class).uploadVideo(
                    createFilePart("videoPicFile",new File(mCoverPath)),
                    createFilePart("videoFile",new File(mPath)),
                    createFormBody(etVideoDesc.getText().toString().trim()),
                    createFormBody(width),
                    createFormBody(height))
                    .enqueue(new JsonResultCallback<Object>(context()) {
                        @Override
                        public void onSuccess(Call<Object> call, Object data) {
                            super.onSuccess(call, data);
                            //.....
                        }
                        @Override
                        public void onFinish(Call<Object> call) {
                            //...
                        }
                    });

    注意: 如果你使用了 GsonRequestBodyConverter 或类似的RequestBodyConverter, 一定记得要略过@Multipart 标注的Service方法, 否则你的File会被转为文件路径的字符串, 这是一个坑

      

    另一种, 自定义FileRequestBodyConverter:

    未完待续...

    相关链接, 这里有实现

    转载请注明出处:http://duwei.cnblogs.com/
  • 相关阅读:
    多表查询练习
    mysql查询练习
    mysql建表练习
    超详细mysql left join,right join,inner join用法分析
    Elasticsearch搜索引擎版本配置
    centos 开启apache rewrite模式
    centos 下 apache 重启启动命令
    centos 下使用sublime
    ThinkPHP Where 条件中使用表达式
    转载自php100中文网 centos下lamp 环境搭建
  • 原文地址:https://www.cnblogs.com/duwei/p/retrofit2_upload_image_file.html
Copyright © 2020-2023  润新知