简体   繁体   English

如何使用 retrofit2 上传图像文件?

[英]How to upload an image file using retrofit2?

I am trying to upload an image from android device to server using Retrofit2 and end up getting error '400 Bad Request'.我正在尝试使用 Retrofit2 将图像从 android 设备上传到服务器并最终收到错误“400 Bad Request”。 Below is the implementation.下面是实现。 Could somebody help to fix the error?有人可以帮助解决错误吗?

Service:服务:

@Multipart
@Headers("Content-type:application/json")
@POST("upload/profile")
Call<JsonObject> changePhotoProfile(@Part MultipartBody.Part partFile);

Here is my code:这是我的代码:

@Override
protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if (resultCode == RESULT_OK && requestCode == 100) {
        if (data != null) {
            Uri uri = data.getData();
            uploadImageToServer(uri);
        }
    }
}

private void uploadImageToServer(Uri uri) {
    MultipartBody.Part partMap = prepareFilePart("file", uri);
    Call<JsonObject> changeImage = baseServiceAPI.changePhotoProfile(partMap);
    changeImage.enqueue(new Callback<JsonObject>() {
        @Override
        public void onResponse(Call<JsonObject> call, Response<JsonObject> response) {
            
        }

        @Override
        public void onFailure(Call<JsonObject> call, Throwable t) {
            
        }
    });
}

private MultipartBody.Part prepareFilePart(String partName, Uri uri) {
    File file = FileUtils.getFile(ProfileActivity.this, uri);
    RequestBody requestBody = RequestBody.create(MediaType.parse(Objects.requireNonNull(getContentResolver().getType(uri))), file);

    return MultipartBody.Part.createFormData(partName, file.getName(), requestBody);
}

1

You can try it without @Headers("Content-type:application/json")您可以在没有@Headers("Content-type:application/json")情况下尝试

like喜欢

@Multipart
@POST("upload/profile")
Call<JsonObject> changePhotoProfile(@Part MultipartBody.Part partFile);

it should work它应该工作

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM