java - 请问怎样用Retrofit通过post把String参数和二进制流一起上传到服务器?
大家讲道理
大家讲道理 2017-04-18 10:40:53
[Java讨论组]
大家讲道理
大家讲道理

光阴似箭催人老,日月如移越少年。

全部回复(3)
伊谢尔伦

我用的 retrofit 版本是 2.1.0。

方法这样定义;
@Multipart
@POST(NetUrlConstant.URL_UPLOAD_PHOTO)
Call<UploadPhotoBean> uploadPhoto(@PartMap Map<String, RequestBody> map);

传入的是个 Map ,下面来创建这个 map :
    File file = new File("图片路径");
    Map<String, RequestBody> map = new HashMap<>();
    map.put("api_key", parseRequestBody("你的参数值");
    map.put("api_secret", parseRequestBody("你的参数值");
    map.put("iamge_url", parseRequestBody("你的参数值");
    map.put("return_landmark", parseRequestBody(你的 int 值+""));//int 也转成 string 生成 Body, 服务端取下来是 int ;
    map.put("return_attributes", parseRequestBody("你的参数值");
    map.put(RetrofitManager.parseImageMapKey("image_file",file.getName()),parseImageRequestBody(file));//这里是你的文件。
    
   上面用到封装的几个方法 :
      public static RequestBody parseRequestBody(String value) {
        return RequestBody.create(MediaType. parse("text/plain"), value);
      }

      public static RequestBody parseImageRequestBody(File file) {
        return RequestBody.create(MediaType. parse("image/*"), file);
      }

      public static String parseImageMapKey(String key, String fileName) {
        return key + "\"; filename=\"" + fileName;
      }
大家讲道理

这个应该是上传图片的情况吧,参数像description,具体看后台需要什么字段添加,不过很奇怪为什么要上传文件又要上传路径,直接上传路径不行?如果是七牛的话,直接上传后拿到地址再提交,还可以加后缀获取缩略图,大概是这样,应该没错,仅供参考

 RequestBody description =RequestBody.create(
MediaType.parse("multipart/form-data"),
 description);

 File file = new File(filepath);//
RequestBody requestBody =RequestBody.create(
MediaType.parse("multipart/form-data"), file);


@Multipart
@POST("[接口地址]")
Call<ShowResultBean> upload(
@Part("myfile\"; filename=\"image.png\" ") RequestBody file,
@Part("description") RequestBody description);
PHP中文网

建议多用搜索引擎
答案来自stackoverflow
retrofit 上传multipart文件包括其他参数

热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 意见反馈 讲师合作 广告合作 最新更新 English
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习
PHP中文网抖音号
发现有趣的

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号