簡體   English   中英

使用改造上傳圖像

[英]Uploading image by using Retrofit

我一直在嘗試通過API從應用程序上傳圖像。 但我一直得到這個作為回應:

{"error":"<p>You did not select a file to upload.<\/p>"}

這是我的代碼:

APIService.java

@Multipart
@POST("/media/upload.html")
Call<UploadImg> uploadimage (@Part MultipartBody.Part file);

UploadImageActivity.java

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);

    if(requestCode == REQUEST_CODE && resultCode == RESULT_OK && data != null && data.getData() != null){
        Uri uri = data.getData();
        Picasso.with(this).load(uri).fit().into(btn_img_picker);

        String imagePath;

        if (data.toString().contains("content:")) {
            imagePath = getRealPathFromURI(uri);
        } else if (data.toString().contains("file:")) {
            imagePath = uri.getPath();
        } else {
            imagePath = null;
        }

        File file = new File(imagePath);

        System.out.println(imagePath);

        RequestBody requestFile = RequestBody.create(MediaType.parse("image/*"), file);

        MultipartBody.Part body = MultipartBody.Part.createFormData("userfile", file.getName(), requestFile);

        System.out.println(file.getName());

        Call<UploadImg> call = mAPIService.uploadimage(body);
        call.enqueue(new Callback<UploadImg>() {
            @Override
            public void onResponse(Call<UploadImg> call, Response<UploadImg> response) {
                System.out.println(response.raw());
            }

            @Override
            public void onFailure(Call<UploadImg> call, Throwable t) {
                System.out.println(t);
            }
        });
    }
}

public String getRealPathFromURI(Uri contentUri) {
    Cursor cursor = null;
    try {
        String[] proj = {MediaStore.Images.Media.DATA};
        cursor = getContentResolver().query(contentUri, proj, null, null,
                null);
        int column_index = cursor
                .getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
        cursor.moveToFirst();
        return cursor.getString(column_index);
    } finally {
        if (cursor != null) {
            cursor.close();
        }
    }
}

我已經測試過以Postman的表單數據發送圖像。 我可以從桌面發送圖片並收到預期的響應。 但是我無法對android中的代碼執行相同的操作。

我發送的圖像路徑格式不正確嗎? 當前,變量imagePath具有以下輸出:

/storage/emulated/0/Download/download.jpg

如果這是不正確的發送路徑,請告訴正確的路徑。 提前致謝。

嘗試這個

 @Multipart @POST("user/updateprofile") Observable<ResponseBody>
 updateProfile(@Part("user_id") RequestBody id, @Part("full_name")
 RequestBody fullName, @Part MultipartBody.Part image, @Part("other")
 RequestBody other); 

這樣通過

File file = new File("/storage/emulated/0/Download/Corrections 6.jpg"); RequestBody
requestFile = RequestBody.create(MediaType.parse("multipart/form-data"), file);
// MultipartBody.Part is used to send also the actual file name
MultipartBody.Part body = MultipartBody.Part.createFormData("image", file.getName(), requestFile);

在多部分請求中添加另一部分

 RequestBody fullName =  RequestBody.create(  MediaType.parse("multipart/form-data"), "Your Name");
 service.updateProfile(id, fullName, body, other)

您可以使用以下代碼上傳圖片

首先,您編寫用於調用請求的代碼

//profile pic is image path
    RequestBody imagePath = Utility.imageToBody(profilePic);

 TestApiInterface service = WebServiceCaller.getClient();
 Call<SuccessResponse> call = service.mediaUpload(imagePath);

 call.enqueue(new Callback<SuccessResponse>() {
                @Override
                public void onResponse(Call<SuccessResponse> call, 
 Response<SuccessResponse> response) {
                    SuccessResponse result;
                    if (response.isSuccessful()) {
                        result = response.body();

                     }
                }

                @Override
                public void onFailure(Call<SuccessResponse> call, Throwable t) {


                }
            });

然后為API編寫代碼

@Multipart
@POST("user/mediaupload")
Call<SuccessResponse> mediaUpload(@Part("media_file\"; filename=\"test_media.png\" ") RequestBody media_file);

然后下面的Imagetobody隱藏的代碼

public static RequestBody imageToBody(String text) {
    RequestBody requestBody;
    if (text != null && text.length() > 0) {
        MediaType MEDIA_TYPE = MediaType.parse("image/*");
        File file = new File(text);
        requestBody = RequestBody.create(MEDIA_TYPE, file);
    } else {
        requestBody = null;
    }
    return requestBody;
}

試試這個我有另一種方法來實現

  • interface內部

@Multipart
   @POST("edit_profile")
   Call<TokenResponse> getTokenAccess(@PartMap Map<String, RequestBody> map);

  • 致電您的Activity

private void getData() {
        Retrofit retrofit=new Retrofit.Builder()
                .baseUrl("your_base_url_here")
                .addConverterFactory(GsonConverterFactory.create())
                .build();
        Click service=retrofit.create(Click.class);
          File file = new File("/storage/sdcard0/Pictures/OGQ/Puskinn Sharma_Jump roof skyscraper_YkRiRWpYcw.jpg");
          //make sure your image path is valid
        String convert_File_2String= String.valueOf(file);
        String fileNAme=convert_File_2String.substring(convert_File_2String.lastIndexOf("/")+1);
        RequestBody fbody = RequestBody.create(MediaType.parse("image/*"), file);
        RequestBody name = RequestBody.create(MediaType.parse("text/plain"), "Sunil");
        RequestBody id = RequestBody.create(MediaType.parse("text/plain"), "56");
        RequestBody lastname= RequestBody.create(MediaType.parse("text/plain"), "Kumar");
        Map<String, RequestBody> map = new HashMap<>();
        map.put("profile_pic\"; filename=\""+fileNAme+"\" ", fbody);
        map.put("firstname", name);
        map.put("user_id", id);
        map.put("lastname",lastname);

    Call<TokenResponse> tokenResponseCall=service.getTokenAccess(map);
    tokenResponseCall.enqueue(new Callback<TokenResponse>() {
        @Override
        public void onResponse(Call<TokenResponse> call, Response<TokenResponse> response) {
            TokenResponse tokenResponse=response.body();
            Log.e("93","MA>>"+tokenResponse.getJwt());
                  }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        @Override
        public void onFailure(Call<TokenResponse> call, Throwable throwable) {
                    Log.e("172","><<>>"+throwable);
            Log.e("TAG", "onFailure: 173"+call.toString() );
        }
    });
}

暫無
暫無

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

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