繁体   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