【问题标题】:Upload Image to server using Retrofit2 POST request使用 Retrofit2 POST 请求将图像上传到服务器
【发布时间】:2016-11-26 17:30:10
【问题描述】:

我想使用 Retrofit2 将我的图库图片上传到服务器。 API 有 1 个参数,其中包含作为表单数据的 flie,另一个参数是带有键的标题。当我将图像上传到服务器时,我从服务器收到 File not found 消息。我正在发送正确的文件名,但我不知道为什么会这样。谁能帮我解决。下面是我的代码。

final ProgressDialog progressDialog;
        progressDialog = new ProgressDialog(UserProfileActivity.this);
        progressDialog.setMessage("Updating Data");
        progressDialog.show();

        //Create Upload Server Client
        ApiService service = RetroClient.getApiService();

        //File creating from selected URL
        File file = new File(imgDecodableString);
        Log.d("TAG","file="+file.getName());
        // create RequestBody instance from file
        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);

        Call<com.example.datamodel.Response> resultCall = service.uploadImage(loginHash,body);

        resultCall.enqueue(new Callback<com.example.datamodel.Response>() {
            @Override
            public void onResponse(Call<com.example.datamodel.Response> call, retrofit2.Response<com.example.datamodel.Response> response) {
                com.example.datamodel.Response mBean = response.body();
                if(null != mBean)
                {
                    Log.d("TAG","RS="+mBean.getMessage());
                    Log.d("TAG","RS="+mBean.getData().getvImage());
                }

                progressDialog.dismiss();
            }

            @Override
            public void onFailure(Call<com.example.datamodel.Response> call, Throwable t) {
                progressDialog.dismiss();
                Log.d("TAG", "fail=" + t.getMessage());
            }
        });

RetroClient.java

public class RetroClient {
public RetroClient() {

}
private static Retrofit getRetroClient() {
    return new Retrofit.Builder()
            .baseUrl(AppConstants.BASE_URL)
            .addConverterFactory(GsonConverterFactory.create())
            .build();
}

public static ApiService getApiService() {
    return getRetroClient().create(ApiService.class);
}}

ApiService.java

public interface ApiService {
@Multipart
@POST("api/User/uploadUserProfilePhoto")
Call<Response> uploadImage(@Header("vLoginHash") String vLoginHash,@Part MultipartBody.Part file);}

在 logcat 中,我收到来自服务器的 File not found 消息。任何人请帮忙。提前致谢。

【问题讨论】:

标签: android image-uploading multipartform-data retrofit2


【解决方案1】:

尝试不使用多部分

 @POST("/api/name.jpg")
        Call<Object> upload(
                @Header("header_name") String authorization,
                @Body RequestBody body);

在 OnActivityREsult 中

      if (resultCode == Activity.RESULT_OK ) {

                Bitmap photo = null;
             if(requestCode==REQUEST_GALLERY){
                    try {
                        photo = MediaStore.Images.Media.getBitmap(getActivity().getApplicationContext().getContentResolver(), data.getData());
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                // CALL THIS METHOD TO GET THE URI FROM THE BITMAP
                if(photo!=null){
                    Uri tempUri = getImageUri(getActivity(), photo);
                    // CALL THIS METHOD TO GET THE ACTUAL PATH
                    File finalFile = new File(getRealPathFromURI(tempUri));
                   RequestBody requestBody = RequestBody.create(MediaType.parse("*/*"), file);
            apimy.upload(header value,requestBody).enque...            
                }
            }

 public Uri getImageUri(Context inContext, Bitmap inImage) {
        ByteArrayOutputStream bytes = new ByteArrayOutputStream();
        inImage.compress(Bitmap.CompressFormat.JPEG, 100, bytes);
        String path = MediaStore.Images.Media.insertImage(inContext.getContentResolver(), inImage, "Title", null);
        return Uri.parse(path);
    }

    public String getRealPathFromURI(Uri uri) {
        Cursor cursor = getActivity().getContentResolver().query(uri, null, null, null, null);
        assert cursor != null;
        cursor.moveToFirst();
        int idx = cursor.getColumnIndex(MediaStore.Images.ImageColumns.DATA);
        return cursor.getString(idx);
    }

这段代码对我来说很好用。

【讨论】:

  • 获取正文参数不能与表单或多部分编码一起使用。
  • 在帖子行上方的界面中删除@Multipart
  • 我已将其删除,但结果相同。
  • in req body .parse(star/star)
  • 你能用uploadImage()方法编辑吗?我已经尝试过,但它不起作用。所以需要看看你的方法是什么
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-03-21
  • 2019-12-20
  • 1970-01-01
  • 2021-07-31
  • 1970-01-01
相关资源
最近更新 更多