如何使用 Retrofit Android 上传图片? [英] How to upload image with Retrofit Android?

查看:81
本文介绍了如何使用 Retrofit Android 上传图片?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a function to request upload image with Retrofit like this

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

                }
            });
}

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

and for the example, I have a button to upload image in my fragment

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

}

我应该输入什么代码

OnChangePictureClicked

OnChangePictureClicked

所以我可以从图库中选择一个图像,然后我向 API 请求它.

So i can choose an image from gallery and then I request it to API.

void uploadPhoto(File file)

void uploadPhoto(File file)

谢谢

推荐答案

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

Transform your image to an array of bytes and then create an Object Dto like the example below and send it to the server through Retrofit.

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

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

}

改造 Api 服务:

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

希望它有效.

这篇关于如何使用 Retrofit Android 上传图片?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆