代码之家  ›  专栏  ›  技术社区  ›  SinaMN75

通过multipartbody.part上传文件

  •  1
  • SinaMN75  · 技术社区  · 6 年前

    我正在使用改型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
    

    我在我的日志中无限循环得到这个错误。 我为从Gallery获取图像而编写的代码:

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

    为了让它进入活动结果:

        @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 回复  |  直到 6 年前
        1
  •  1
  •   Shaon    6 年前

    遵循以下两种方法。 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) {
    
            }
        });
    }