美文网首页
retrofit2 rxjava 上传图片,文件名称的key怎么

retrofit2 rxjava 上传图片,文件名称的key怎么

作者: 一个冬季 | 来源:发表于2018-07-31 12:54 被阅读51次

    最近在弄上传图片的功能,后台给的接口内容如下:

    http://xxxxxxxxxx/UpdateUserName.php?UserID=12341213123&PassKey=1s2d4gju7t&ObjectUserID=1300
    

    然后还要携带参数,需要带如下参数
    UserID,PassKey,ObjectRoleID,RolePhoto(File),S_RolePhoto(File)
    如你们所见,在上面的链接里面已经含有了3个参数了,剩下的是要传递文件RolePhoto和S_RolePhoto。整个的请求是post请求
    感谢这篇博客Retrofit2+RxJava学习小计(一):单文件、多文件上传之填平的坑
    给我提供了上传图片的解决办法。
    我们一百度,一google,里面全是说怎么上传上传图片的大体的内容如下

        @Multipart
        @POST("接口")
        Observable<ResponseBody> upload(@Part MultipartBody.Part RolePhoto,@Part MultipartBody.Part S_RolePhoto);
    
       File file = null;
        try {
            file = new File(path);
        } catch (URISyntaxException e) {
            e.printStackTrace();
        }
        RequestBody requestBody = RequestBody.create(MediaType.parse("multipart/form-data"), file);
        MultipartBody.Part body = MultipartBody.Part.createFormData("file", file.getName(), requestBody);
    

    但是我们直接copy下来用,你会发现不行,为啥,因为我们后台接收的参数不全是名称为file字段啊,那么就只能修改了,怎么修改?后台说需要名称为RolePhoto和S_RolePhoto这2个图片

       File file = null;
        try {
            file = new File(path);
        } catch (URISyntaxException e) {
            e.printStackTrace();
        }
        RequestBody requestBody = RequestBody.create(MediaType.parse("multipart/form-data"), file);
        MultipartBody.Part  RolePhotoBody = MultipartBody.Part.createFormData("RolePhoto", file.getName(), requestBody);
    
      File file2 = null;
        try {
            file2 = new File(path2);
        } catch (URISyntaxException e) {
            e.printStackTrace();
        }
      RequestBody requestBody = RequestBody.create(MediaType.parse("multipart/form-data"), file2);
        MultipartBody.Part  S_RolePhotoBody = MultipartBody.Part.createFormData("S_RolePhoto", file2.getName(), requestBody);
    

    OK这样后台就能接收到名称为,RolePhoto,S_RolePhoto参数的字段。但是你说哎呀,其他UserID,PassKey,ObjectRoleID参数都是在url后面的啊。那么你改下api就可以了

        @Multipart
        @POST("接口)
        Observable<ResponseBody>  upload(@Part MultipartBody.Part RolePhoto, @Part MultipartBody.Part S_RolePhoto
                , @Query("UserID") String UserID, @Query("PassKey") String PassKey, @Query("ObjectRoleID") String ObjectRoleID);
    

    相关文章

      网友评论

          本文标题:retrofit2 rxjava 上传图片,文件名称的key怎么

          本文链接:https://www.haomeiwen.com/subject/wfycvftx.html