通过MultipartBody.Part上传文件

时间:2018-08-14 16:22:54

标签: android image file retrofit multipart

我正在使用翻新2上传文件,我的一个问题是当我尝试从URI中获取文件时出现错误:

W/System.err: stat failed: ENOENT (No such file or directory) : /external/images/media/1838
          stat failed: ENOENT (No such file or directory) : /external/images/media/1838
          stat failed: ENOENT (No such file or directory) : /external/images/media/1838

,并且在日志中出现无限循环错误。 我为从图库获取图像而编写的代码:

        imageViewUpdateProfileActivity.setOnClickListener(view -> {
        Intent intent = new Intent();
        intent.setType("image/*");
        intent.setAction(Intent.ACTION_GET_CONTENT);
        startActivityForResult(intent, 1);
    });

,并在onActivityResult中获取它:

    @Override
protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if (requestCode == 1 && resultCode == RESULT_OK) {
        File file = new File(Objects.requireNonNull(Objects.requireNonNull(data).getData()).getPath());
        MultipartBody.Part filePart = MultipartBody.Part.createFormData("image", file.getName(), RequestBody.create(MediaType.parse("image/*"), file));
        RequestBody fullname = RequestBody.create(MediaType.parse("text/plain"), editTextFullNameUpdateProfileActivity.getText().toString());
        RequestBody Gender = RequestBody.create(MediaType.parse("text/plain"), gender);
        RequestBody aboutMe = RequestBody.create(MediaType.parse("text/plain"), editTextAboutMeUpdateProfileActivity.getText().toString());

        ApiClient.getClient().create(ApiService.class).updateProfilePhoto(App.userProfile.getUsername(), filePart, fullname, Gender, aboutMe).enqueue(new Callback<ResponseBody>() {
            @Override
            public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
            }

            @Override
            public void onFailure(Call<ResponseBody> call, Throwable t) {
            }
        });
    }
}

1 个答案:

答案 0 :(得分:1)

请按照以下两种方法进行操作。 Here is the full tutorial link

 @Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    try {
        // When an Image is picked
        if (requestCode == 0 && resultCode == RESULT_OK && null != data) {

            // Get the Image from data
            Uri selectedImage = data.getData();
            String[] filePathColumn = {MediaStore.Images.Media.DATA};

            Cursor cursor = getContentResolver().query(selectedImage, filePathColumn, null, null, null);
            assert cursor != null;
            cursor.moveToFirst();

            int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
            mediaPath = cursor.getString(columnIndex);
            // Set the Image in ImageView for Previewing the Media
            imgView.setImageBitmap(BitmapFactory.decodeFile(mediaPath));
            cursor.close();

        } else {
            Toast.makeText(this, "You haven't picked Image/Video", Toast.LENGTH_LONG).show();
        }
    } catch (Exception e) {
        Toast.makeText(this, "Something went wrong", Toast.LENGTH_LONG).show();
    }

}



// Uploading Image/Video
private void uploadFile() {
    progressDialog.show();

    // Map is used to multipart the file using okhttp3.RequestBody
    File file = new File(mediaPath);

    // Parsing any Media type file
    RequestBody requestBody = RequestBody.create(MediaType.parse("*/*"), file);
    MultipartBody.Part fileToUpload = MultipartBody.Part.createFormData("file", file.getName(), requestBody);
    RequestBody filename = RequestBody.create(MediaType.parse("text/plain"), file.getName());

    ApiService getResponse = ApiClient.getClient().create(ApiService.class);
    Call<ServerResponse> call = getResponse.uploadFile(fileToUpload, filename);
    call.enqueue(new Callback<ServerResponse>() {
        @Override
        public void onResponse(Call<ServerResponse> call, Response<ServerResponse> response) {
            ServerResponse serverResponse = response.body();
            if (serverResponse != null) {
                if (serverResponse.getSuccess()) {
                    Toast.makeText(getApplicationContext(), serverResponse.getMessage(),Toast.LENGTH_SHORT).show();
                } else {
                    Toast.makeText(getApplicationContext(), serverResponse.getMessage(),Toast.LENGTH_SHORT).show();
                }
            } else {
                assert serverResponse != null;
                Log.v("Response", serverResponse.toString());
            }
            progressDialog.dismiss();
        }

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

        }
    });
}