Hello there i am trying to download a pdf file with dio library but in the end i get this errror:
Hello there i am trying to download a pdf file with dio library but in the end i get this errror:
I/flutter (19900): 100%
I/flutter (19900): connection: keep-alive
I/flutter (19900): last-modified: Mon, 17 Oct 2022 10:17:34 GMT
I/flutter (19900): cache-control: no-cache, no-store, max-age=0, must-revalidate
I/flutter (19900): date: Fri, 21 Oct 2022 07:39:15 GMT
I/flutter (19900): vary: Origin
I/flutter (19900): vary: Access-Control-Request-Method
I/flutter (19900): vary: Access-Control-Request-Headers
I/flutter (19900): content-type: text/html;charset=UTF-8
I/flutter (19900): pragma: no-cache
I/flutter (19900): x-xss-protection: 1; mode=block
I/flutter (19900): content-language: en
I/flutter (19900): server: nginx/1.15.12
I/flutter (19900): accept-ranges: bytes
I/flutter (19900): content-length: 6425
I/flutter (19900): x-frame-options: DENY
I/flutter (19900): x-content-type-options: nosniff
I/flutter (19900): expires: 0
I/flutter (19900): FileSystemException: Cannot open file, path = '/data/user/0/com.iccs.electromobilityapp/cache' (OS Error: Is a directory, errno = 21)
Here is my code:
Future download2(Dio dio, String url, String savePath) async {
Directory tempDir = await getTemporaryDirectory();
tempPath = tempDir.path;
String? token = await this.widget.appController.storage.read(key: "token");
Map<String, String> headers = {
"Content-Type": "application/json",
"Accept": "application/json",
"Authorization": "Bearer " (token ?? ""),
};
try {
Response response = await dio.get(
url,
onReceiveProgress: showDownloadProgress,
//Received data with List<int>
options: Options(
headers: headers,
responseType: ResponseType.bytes,
followRedirects: false,
validateStatus: (status) {
return status! < 500;
}),
);
print(response.headers);
new File('$tempPath/file.xlsx').create(recursive: true);
File file = File(tempPath);
var raf = file.openSync(mode: FileMode.write);
// response.data is List<int> type
raf.writeFromSync(response.data);
await raf.close();
} catch (e) {
print(e);
}
}
CodePudding user response:
I've written a simple function for you just pass a url and filename as an argument
downloadedFile({required String url, required String filename}) async {
var downloadsDirectoryPath = await getTemporaryDirectory()
final File file = File("/${downloadsDirectoryPath!.path}/$filename");
final response = await Dio().get(url, onReceiveProgress: (received, total) {
},
options: Options(
responseType: ResponseType.bytes,
followRedirects: false,
receiveTimeout: 0,
));
final raf = file.openSync(mode: FileMode.write);
raf.writeFromSync(response.data);
await raf.close();
return file;
}
Note: upvote and make the answer as correct if you find it useful.