我正在此地址下载一个pdf文件:
/storage/emulated/0/documents/download folder/2021-08-30-16:37:55.544095iH46x.pdf它在android 10和更低版本中运行得很好。但是在android 11上我得到了这个错误:
FileSystemException: Cannot open file, path = '/storage/emulated/0/documents/download folder/2021-08-30-16:37:55.544095iH46x.pdf' (OS Error: Operation not permitted, errno = 1)这些是我对清单的权限:
<uses-permission android:name="android.permission.MANAGE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>这些是我对权限处理程序的权限:
Map<Permission, PermissionStatus> result = await [
Permission.storage,
Permission.manageExternalStorage,
Permission.mediaLibrary].request();完整代码:
String fullPath;
try {
Map<Permission, PermissionStatus> result = await [
Permission.storage,
Permission.manageExternalStorage,
Permission.mediaLibrary].request();
if (result[Permission.storage].isGranted && result[Permission.manageExternalStorage].isGranted && result[Permission.mediaLibrary].isGranted ) {
// a custom method for getting path
String dir = await Utility.makeAndGetDownloadFolder();
// preparing access token
final storage = Storage.FlutterSecureStorage();
String accessToken = await storage.read(key: "accessToken");
// generating random string for the pdf file name
String dateNow = DateTime.now().toString();
dateNow = dateNow.replaceAll(' ', '');
String randomName = dateNow + Utility.getRandomString(5);
fullPath = "$dir/$randomName.pdf";
// preparing dio request
String url;
Dio dio = Dio();
Response response;
url = "https://www.example.com/api/downloadFile";
FormData formData = FormData.fromMap({
"idAdvertise": idAdvertise,
});
response = await dio.post(url,
data: formData,
options: Options(
headers: {
HttpHeaders.authorizationHeader: 'Bearer $accessToken',
},
responseType: ResponseType.bytes,
followRedirects: false,
validateStatus: (status) {
return status < 500;
}), onReceiveProgress: (int received, int total) {
if (total != -1) {
setState(() {
_progress = received / total * 100;
});
}
});
if (response.statusCode == 200) {
File file = File(fullPath);
// code reach untill here and then it jumps in catch
var raf = file.openSync(mode: FileMode.write);
raf.writeFromSync(response.data);
await raf.close();
// show notification on success
await showNotification(fullPath);
}else if(response.statusCode == 404){
// status code 404 do something
print("status 404");
}else{
print("status code download is ${response.statusCode}");
Components.customSnackBar(context,AppStr.errDownloadFailed403);
}
setState(() {
});
}
} catch (e) {
print("catch is $e");
}请不要建议我使用path_provider,因为这不是我所需要的
发布于 2022-03-06 10:42:18
对于那些仍然想知道我如何解决这个问题的人,我使用路径提供程序将文件保存在缓存中,然后在保存文件之后,将该文件移动到对话框包的下载文件夹中。
源代码:
//getting the cache directory from path_provider
Directory dir = await getApplicationDocumentsDirectory();
final storage = Storage.FlutterSecureStorage();
String accessToken = await storage.read(key: "accessToken");
var fileName = Utility.generateRandomFileName();
fullPath = "${dir.path}/$fileName.pdf";
bool checkFileExist = true;
while (checkFileExist) {// if file already exists with this name then we generate different name
if (await File(fullPath).exists()) {
fileName = Utility.generateRandomFileName();
fullPath = "${dir.path}/$fileName.pdf";
} else {
checkFileExist = false;
}
}
Dio dio = Dio();
Response response;
FormData formData;
formData = FormData.fromMap({
"id": widget.id,
});
response = await dio.post('https://example.com/downloadfile',
data: formData,
options: Options(
headers: {
HttpHeaders.authorizationHeader: 'Bearer $accessToken',
},
responseType: ResponseType.bytes,
followRedirects: false,
validateStatus: (status) {
return status < 500;
}),
onReceiveProgress: (int received, int total) {
if (total != -1) {
setState(() {
_progressDownloading = received / total * 100;
});
}
});
if (response.statusCode == 200) {
File file = File(fullPath);
var raf = file.openSync(mode: FileMode.write);
raf.writeFromSync(response.data);
await raf.close();
// moving the file from cache to anywhere you want
final params = SaveFileDialogParams(sourceFilePath: fullPath);
await FlutterFileDialog.saveFile(params: params).then((value) async {
if(value != null){//if the file saved successfully
await showNotification();
}else{
print('error couldnt move the pdf file');
}
});
file.delete();//deleting the pdf from cache
}else{
print('something went wrong');
}https://stackoverflow.com/questions/68984682
复制相似问题