使用Retrofit上传图像时出现FileNotFoundException

时间:2018-02-12 07:46:58

标签: android retrofit2 image-uploading multipart

我尝试使用Retrofit上传图片但我收到此错误:

Unable to submit post to API: java.io.FileNotFoundException: /document/image:30231: open failed: ENOENT (No such file or directory)

我的界面是这样的:

public interface MyService{
    @Multipart
    @POST("/url")
    Call<ResponseBody> addNewEvent( @Part("case_Id") int caseId,@Part MultipartBody.Part(file);
}

点击按钮,调用selectImage()函数:

private void selectImage() {
    Intent intent = new Intent();
    intent.setType("image/*");
    intent.setAction(Intent.ACTION_GET_CONTENT);
    startActivityForResult(Intent.createChooser(intent, "Please select image",1);
}

onActivityResult部分,我做了以下事情:

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (requestCode == 1 && resultCode!=RESULT_CANCELED && resultCode == RESULT_OK && data != null && data.getData() != null) {
        FilePathUri = data.getData();
        doAddNewEvent();
    }
}

从上面,调用doAddNewEvent()函数:

public void doAddNewEvent() {
    File file = new File(FilePathuri.getPath());
    RequestBody requestFile=RequestBody.create(MediaType.parse("multipart/form-data"), file);
    MultipartBody.Part body = MultipartBody.Part.createFormData("image", file.getName(), requestFile);

 apiService.addNewEvent(inputCaseId, body).enqueue(new Callback<ResponseBody>() {
        @Override
        public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
            if (response.isSuccessful()) {                    
                ResponseBody addEventResponse = response.body();
                Log.d("as", "response: " + addEventResponse);
                finish();
            }
        }

        @Override
        public void onFailure(Call<ResponseBody> call, Throwable t) {
            Log.e("as", "Unable to submit post to API");
        }
    });
}

1 个答案:

答案 0 :(得分:1)

获取文件路径存在问题

试试这个:

if (requestCode == 1 && resultCode!=RESULT_CANCELED && resultCode == RESULT_OK && data != null && data.getData() != null) {

            FilePathStr = null;

            if (data != null) {



                Uri selectedImage = data.getData();
                String[] filePath = {MediaStore.Images.Media.DATA};
                Cursor c = getContentResolver().query(selectedImage, filePath,
                        null, null, null);
                c.moveToFirst();
                int columnIndex = c.getColumnIndex(filePath[0]);
                FilePathStr = c.getString(columnIndex);
                c.close();
                doAddNewEvent();




            }

        }

使用字符串路径生成多部分

MultipartBody.Part body = null;

            if (FilePathStr != null) {
                File file = new File(FilePathStr );
                RequestBody reqFile = RequestBody.create(MediaType.parse("image/*"), file);
                body = MultipartBody.Part.createFormData("image", file.getName(), reqFile);

            }