【问题标题】:Upload image with retrofit 2上传带有改造 2 的图像
【发布时间】:2017-09-07 05:51:46
【问题描述】:

界面:

@Multipart
@POST("emp/passportupload")
Single<ApiResponse> uploadPassportImage(@Query("passportnumber") String passportNumber, @Part MultipartBody.Part file);

调用api:

File file = new File(model.getImage().getPath());
if (!file.exists()) return null;
RequestBody requestBody = RequestBody.create(MediaType.parse("image/*"), file);
MultipartBody.Part filePart = MultipartBody.Part.createFormData(ApiConstant.PICTURE_UPLOAD_PARAM, file.getName(), requestBody);

dataService.uploadPassportImage(map, filePart)
                .subscribeOn(Schedulers.newThread())
                .observeOn(AndroidSchedulers.mainThread());

我正在使用此方法将图像上传到服务器,但服务器无法将其验证为图像,因此给了我这样的响应

“提供的文件不是有效图片。请提供 PNG/JPG 文件”

但是,我已经通过邮递员上传了相同的图像文件,并且成功了。这是请求:(注意:passportnumber 是一个参数,而不是表单数据)

【问题讨论】:

    标签: android retrofit2 image-uploading


    【解决方案1】:
    @Multipart
    @POST("changeCompanyLogo")
    Call<ChangeLogoResponse> changeCompanyLogo(@Part MultipartBody.Part image, @Part("JSON") RequestBody name);
    

    在服务中编写此代码

    ChangeLogoAPI service = ServiceHandler.getClient().create(ChangeLogoAPI.class);
            File file = new File(intent.getStringExtra("imagePath"));
            RequestBody reqFile = RequestBody.create(MediaType.parse("multipart/form-data"), file);
            MultipartBody.Part body = MultipartBody.Part.createFormData("companyLogo", file.getName(), reqFile);
            RequestBody name = RequestBody.create(MediaType.parse("text/plain"), new Gson().toJson(new ChangeLogoParams()));
            Call<ChangeLogoResponse> call = service.changeCompanyLogo(body, name);
            call.enqueue(new Callback<ChangeLogoResponse>() {
                @Override
                public void onResponse(Call<ChangeLogoResponse> call, Response<ChangeLogoResponse> response) {
                    Log.d(TAG, "response: " + response.isSuccessful());
    
    
                }
    
                @Override
                public void onFailure(Call<ChangeLogoResponse> call, Throwable t) {
    
                }
            });
    

    【讨论】:

      【解决方案2】:
      @POST("{path}")
      Call<Void> uploadFile(@Header("Content-Type") String type,  @Body RequestBody photo,  @Path("path") String path);
      
      
          File file = new File("YOUR_FILE_URI");
      
          String filename = file.getName();
          String fileExtension = MimeTypeMap.getFileExtensionFromUrl(Uri.fromFile(file).toString());
          final String type = MimeTypeMap.getSingleton().getMimeTypeFromExtension(fileExtension);
      
      
          InputStream in = null;
          RequestBody requestBody = null;
          try {
              in = new FileInputStream(file);
              byte[] buf;
              buf = new byte[in.available()];
              while (in.read(buf) != -1);
              requestBody = RequestBody.create(MediaType.parse("application/octet-stream"), buf);
      
          } catch (FileNotFoundException e) {
              e.printStackTrace();
          } catch (IOException e) {
              e.printStackTrace();
          }
      
          ApiConfig getResponse = AppConfig.getRetrofit().create(ApiConfig.class);
          Call<Void> call = getResponse.uploadFile(type, requestBody , posturl);
      

      【讨论】:

        【解决方案3】:

        你可以这样尝试,你需要将地图参数设置为multipart 看看下面的例子,我同时传递了 userId 和 image

        RequestBody requestBody = RequestBody.create(MediaType.parse("*/*"), file);
        
        MultipartBody.Part fileToUpload = MultipartBody.Part.createFormData("image", file.getName(), requestBody);
        MultipartBody.Part id = MultipartBody.Part.createFormData("userId", userId);
        Call<ProfilePicUpdateResponse> call = apiService.updateProfilePic(id,fileToUpload);
        

        【讨论】:

        • 在我的例子中,区别在于 userid 不是来自数据,它是一个参数。我已经尝试过这个解决方案,并且由于服务器找不到参数值而得到错误响应。
        【解决方案4】:

        使用这个很棒的库:[在后台轻松上传文件(FTP / Multipart / Binary),并带有进度指示通知]https://github.com/gotev/android-upload-service/wiki/Setup它将为您完成其余的工作。

        【讨论】:

          猜你喜欢
          • 2016-12-15
          • 2016-04-10
          • 2018-04-15
          • 1970-01-01
          • 1970-01-01
          • 2020-11-17
          • 2017-11-02
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多