如何使用Retrofit Android上传图片?

时间:2017-02-20 06:49:52

标签: android retrofit retrofit2

我有一个功能,可以像这样使用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(文件文件)

谢谢

3 个答案:

答案 0 :(得分: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);

希望它有效。

答案 1 :(得分:0)

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

private Uri selectedImage;

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

     @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()));
           }
        }

答案 2 :(得分:0)

您可以使用multipart进行改造,请使用改造查看此图片上传示例,最适合您。

它为我工作。

//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/