簡體   English   中英

如何使用 retrofit2 上傳圖像文件?

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

我正在嘗試使用 Retrofit2 將圖像從 android 設備上傳到服務器並最終收到錯誤“400 Bad Request”。 下面是實現。 有人可以幫助解決錯誤嗎?

服務:

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

這是我的代碼:

@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

您可以在沒有@Headers("Content-type:application/json")情況下嘗試

喜歡

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

它應該工作

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM