问题
I am using the DownloadManager to download a file to my Android device. I can choose to download to the DCIM, Downloads, Picutures folder, etc using:
downloadRequest.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, "file.jpg");
This works. But I can only choose a limit set of folders to download to. I want to download to the root of my sdcard using /sdcard/
I tried:
downloadRequest.setDestinationUri(Uri.fromFile(new File("/sdcard/file.jpg")));
But this renders the following exception:
IllegalStateException: android invalid combination of destination: 4, path: /sdcard/file.jpg
How can I do this? I have all the required permissions set.
回答1:
Try like this.
downloadRequest.setDestinationInExternalPublicDir("/folderName",file.jpg);
This will create a folder in you external storage root and place the file.jpg in it.
回答2:
Fixed it by using
request.setDestinationInExternalPublicDir( "/APP_NAME/", FileNameGetter.getFileName(DATA..url) );
回答3:
As per the official documentation, you should only use either of the following variants, using one of the available Environment.DIRECTORY_* constants:
myRequest.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, "my_sub_folder/my_file.txt");
where the directory type (i.e. the first parameter) may not be null
, or
myRequest.setDestinationInExternalFilesDir(myContext, null, "my_sub_folder/my_file.txt");
// or
// myRequest.setDestinationInExternalFilesDir(myContext, Environment.DIRECTORY_PICTURES, "my_sub_folder/my_picture.jpg");
where the directory type (i.e. the second parameter) may be null
.
In any case, specifying a (sub)folder in the last parameter is optional.
来源:https://stackoverflow.com/questions/12971684/download-file-to-custom-directory