I'm getting the following error while trying to upload an Image to a server using retrofit, the api receives a header authorization token, _method = "put" and image = "imageName.jpg" as parameters, everything else is optional, any help would be appreciated.
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();
}
});
}
Interface:
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);
}
Retrofit Builder Class:
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;
}
}
For Below Android 6.0 Marshmallow :
Add Permission in Manifest :
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
For Marshmallow and Above Device's:
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
}
}
}
For more info see below link's
Android 6.0 Marshmallow. Cannot write to SD Card
Read and Write permission for storage and gallery usage for marshmallow
Note: Do not forget to add permission in manifest file
Add this
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
inside the manifest tag of your manifest file.Makes sure its outside the application tag however.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.