【问题标题】:How to upload image with Retrofit Android?如何使用 Retrofit Android 上传图片?
【发布时间】:2017-02-20 06:49:52
【问题描述】:

我有一个功能可以像这样使用 Retrofit 请求上传图片

void uploadPhoto(File file) {
    RequestBody photo = RequestBody.create(MediaType.parse("application/image"), file);
    RequestBody body = new MultipartBuilder()
            .type(MultipartBuilder.FORM)
            .addFormDataPart("photo", file.getName(), photo)
            .build();

    fragment.showProgressDialog(fragment.loading);
    fragment.getApi().uploadPhoto(PrefHelper.getString(PrefKey.TOKEN), body)
            .observeOn(AndroidSchedulers.mainThread())
            .subscribeOn(Schedulers.io())
            .subscribe(new Observer<GenericResponse>() {
                @Override
                public void onCompleted() {

                }

                @Override
                public void onError(Throwable e) {
                    fragment.dismissProgressDialog();
                    Timber.e(e.getMessage());
                }

                @Override
                public void onNext(GenericResponse response) {
                    fragment.dismissProgressDialog();

                    if (response.getCode() == 1) {
                        fragment.showSuccessDialog("Saving success", false);
                        userInfo();
                    }

                }
            });
}

例如,我有一个按钮可以在我的片段中上传图片

  @OnClick(R.id.btnChangePicture)
    void onChangePictureClicked() {

}

我应该输入什么代码

OnChangePictureClicked

所以我可以从图库中选择一张图片,然后向 API 请求它。

void uploadPhoto(文件文件)

谢谢

【问题讨论】:

  • 那么您在获取图像源或上传到服务器时遇到了问题?
  • 我的问题是获取图片来源@TruongHieu
  • 您能否提供更多关于您尝试获取的来源的信息?比如画廊或相机之类的......?
  • 我想从我的画廊中拍摄一张图片。并从图库中获取该图像以将其上传到服务器@TruongHieu

标签: android retrofit retrofit2


【解决方案1】:

将图像转换为字节数组,然后像下面的示例一样创建一个 Object Dto,并通过 Retrofit 将其发送到服务器。

@Data
public class SetProfileImageRequestDto {
    @SerializedName("Token")
    private String token;

    @SerializedName("Stream")
    private byte[] image;

}

改造 Api 服务:

    @POST("SetProfileImage/")
    Observable<ResultResponseDto> setProfileImage(@Body SetProfileImageRequestDto profileImageRequestDto);

希望它有效。

【讨论】:

【解决方案2】:

在 Activity 或 Fragment 中创建一个 Uri 对象。

private Uri selectedImage;

之后,您将在 onActivityResult 中获得图库结果。

     @Override
            protected void onActivityResult(int requestCode, int resultCode, Intent data) {
                super.onActivityResult(requestCode, resultCode, data);
                if (requestCode == RESULT_LOAD_IMAGE && resultCode == RESULT_OK && null != data) {
                   selectedImage = data.getData();
                }
            }

然后在你的 onChangePictureClicked 方法中。

    @OnClick(R.id.btnChangePicture)
        void onChangePictureClicked() {
           if(selectedImage !=null){
             uploadPhoto(new File(selectedImage.getPath()));
           }
        }

【讨论】:

    【解决方案3】:

    您可以使用带有改造的多部分,请看这个使用改造的图像上传示例,它最适合您。

    它对我有用。

    //Create Upload Server Client
            ApiService service = RetroClient.getApiService();
    
            //File creating from selected URL
            File file = new File(imagePath);
    
            // create RequestBody instance from file
            RequestBody requestFile = RequestBody.create(MediaType.parse("multipart/form-data"), file);
    
            MultipartBody.Part body =
                    MultipartBody.Part.createFormData("uploaded_file", file.getName(), requestFile);
    
            Call<Result> resultCall = service.uploadImage(body);
    
            resultCall.enqueue(new Callback<Result>() {
                @Override
                public void onResponse(Call<Result> call, Response<Result> response) {
    
                    progressDialog.dismiss();
    
                    // Response Success or Fail
                    if (response.isSuccessful()) {
                        if (response.body().getResult().equals("success"))
                            Snackbar.make(parentView, R.string.string_upload_success, Snackbar.LENGTH_LONG).show();
                        else
                            Snackbar.make(parentView, R.string.string_upload_fail, Snackbar.LENGTH_LONG).show();
    
                    } else {
                        Snackbar.make(parentView, R.string.string_upload_fail, Snackbar.LENGTH_LONG).show();
                    }
    
                    /**
                     * Update Views
                     */
                    imagePath = "";
                    textView.setVisibility(View.VISIBLE);
                    imageView.setVisibility(View.INVISIBLE);
                }
    
                @Override
                public void onFailure(Call<Result> call, Throwable t) {
                    progressDialog.dismiss();
                }
            });
    
    http://www.pratikbutani.com/2016/06/android-upload-image-file-using-retrofit-2-0/
    

    【讨论】:

    • 有 Rx Java Observable 的例子吗?
    猜你喜欢
    • 2020-05-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-06-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-02-22
    相关资源
    最近更新 更多