Android使用Retrofit multipart上传图片时遇到问题?

时间:2017-05-01 03:12:45

标签: java android android-studio retrofit retrofit2

尝试使用改造将图像上传到服务器时出现以下错误,api收到标头授权令牌,_method =“put”和image =“imageName.jpg”作为参数,其他一切都是可选的,任何帮助将不胜感激。

  

java.io.FileNotFoundException:/storage/emulated/0/Download/space-wallpaper-21.jpg:open failed:EACCES(Permission denied)

userImage.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            galleryIntent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
            galleryIntent.setType("*/*");
            startActivityForResult(galleryIntent, RESULT_LOAD_IMG);
        }
    });

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);

    if (requestCode == RESULT_LOAD_IMG && resultCode == RESULT_OK && null != data) {

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

        // Get the cursor
        Cursor cursor = getContentResolver().query(selectedImage,
                filePathColumn, null, null, null);
        // Move to first row
        cursor.moveToFirst();

        int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
        imageDecodableString = cursor.getString(columnIndex);
        cursor.close();

        StringBuilder stringBuilder = new StringBuilder(AUTHORIZATION);

        sharedPreferences = this.getSharedPreferences(getResources().getString(R.string.token), 0);
        stringBuilder.append(sharedPreferences.getString(getResources().getString(R.string.token), ""));

        methodMap.put("_method", "PUT");

        File file = new File(imageDecodableString);
        RequestBody requestBody = RequestBody.create(MediaType.parse("image/*"), file);
        MultipartBody.Part body = MultipartBody.Part.createFormData("image", file.getName(), requestBody);
        //RequestBody name = RequestBody.create(MediaType.parse("text/plain"), "image");

        Call<UserInfo> uploadImage = new RestClient(CONSTS.BASE_URL_ADDRESS_ACCOUNT_CREATION).getUserSignUpClient()
                .postImage(stringBuilder.toString(), methodMap, body);

        uploadImage.enqueue(new Callback<UserInfo>() {
            @Override
            public void onResponse(Call<UserInfo> call, Response<UserInfo> response) {

                if (response.isSuccessful()) {

                }

            }

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

                Toast.makeText(DetailActivity.this, t.getMessage(), Toast.LENGTH_SHORT).show();

            }
        });
    }

接口:

public interface UserSignUpClient {

@POST("account")
Call<AuthenticationAccountCreationResponse> createAccount(@Body UserSignUp userSignUp);

@Multipart
@POST("account")
Call<UserInfo> postImage(@Header("Authorization") String headerValue, @PartMap Map<String, String> map, @Part MultipartBody.Part image);
}

改造构建器类:

public class RestClient {

private UserSignInClient userSignInClient;
private UserSignUpClient userSignUpClient;
private UserInfoClient userInfoClient;
private UserImageUploadClient userImageUploadClient;

public RestClient(String baseUrlLink){

    Retrofit retrofit = new Retrofit.Builder()
            .baseUrl(baseUrlLink)
            .addConverterFactory(GsonConverterFactory.create()).build();

    if (baseUrlLink.equals(CONSTS.BASE_URL_ADDRESS_TOKEN)){

        userSignInClient = retrofit.create(UserSignInClient.class);
    } else if (baseUrlLink.equals(CONSTS.BASE_URL_ADDRESS_ACCOUNT_CREATION)) {

        userSignUpClient = retrofit.create(UserSignUpClient.class);
    } else if (baseUrlLink.equals(CONSTS.BASE_URL_ADDRESS_USER_INFO)){

        userInfoClient = retrofit.create(UserInfoClient.class);
    }
}

public UserSignInClient getUserSignInClient() {
    return userSignInClient;
}

public UserSignUpClient getUserSignUpClient() {
    return userSignUpClient;
}

public UserInfoClient getUserInfoClient() {
    return userInfoClient;
}
}

2 个答案:

答案 0 :(得分:4)

适用于Android 6.0 Marshmallow:

在Manifest中添加权限:

   <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
   <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />

适用于棉花糖及以上设备:

    public class MainActivity extends AppCompatActivity implements ActivityCompat.OnRequestPermissionsResultCallback{

  private static final int REQUEST_WRITE_PERMISSION = 786;

  @Override
  public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
    if (requestCode == REQUEST_WRITE_PERMISSION && grantResults[0] == PackageManager.PERMISSION_GRANTED) {            
        openFilePicker();//do your job
    }
  }

  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    requestPermission();
  }

  private void requestPermission() {
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
        requestPermissions(new String[]{android.Manifest.permission.WRITE_EXTERNAL_STORAGE}, REQUEST_WRITE_PERMISSION);
    } else {
        openFilePicker();//do your job
    }
  }
}

有关详细信息,请参阅以下链接

Android 6.0 Marshmallow. Cannot write to SD Card

Read and Write permission for storage and gallery usage for marshmallow

注意:不要忘记在清单文件中添加权限

答案 1 :(得分:3)

添加此

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>

在清单文件的清单标记内。但是确保它在应用程序标记之外。