Bill Tertis
Bill Tertis

Reputation: 207

How to download pdf file with dio library? Flutter/Dart

Hello there i have made the below code but when i press the download button nothing happens, here is my code:

Code:

    Future download2(Dio dio, String url, String savePath) async {
    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);
      File file = File(savePath);
      var raf = file.openSync(mode: FileMode.write);
      // response.data is List<int> type
      raf.writeFromSync(response.data);
      await raf.close();
    } catch (e) {
      print(e);
    }
  }
  void showDownloadProgress(received, total) {
    if (total != -1) {
      print((received / total * 100).toStringAsFixed(0) + "%");
    }
  }

ElevatedButton(child: Text('Download Bill pdf'),
                onPressed: ()  async {
                  var tempDir = await getTemporaryDirectory();
                  String fullPath = tempDir.path + "/boo2.pdf'";
                  print('full path ${fullPath}');
                  download2(dio, pdfUrl, fullPath);
                })

Console:

I/flutter (24548): full path /data/user/0/com.iccs.electromobilityapp/cache/boo2.pdf'
I/flutter (24548): 100%
I/flutter (24548): connection: keep-alive
I/flutter (24548): last-modified: Mon, 17 Oct 2022 10:17:34 GMT
I/flutter (24548): cache-control: no-cache, no-store, max-age=0, must-revalidate
I/flutter (24548): date: Fri, 21 Oct 2022 08:58:48 GMT
I/flutter (24548): vary: Origin
I/flutter (24548): vary: Access-Control-Request-Method
I/flutter (24548): vary: Access-Control-Request-Headers
I/flutter (24548): content-type: text/html;charset=UTF-8
I/flutter (24548): pragma: no-cache
I/flutter (24548): x-xss-protection: 1; mode=block
I/flutter (24548): content-language: en
I/flutter (24548): server: nginx/1.15.12
I/flutter (24548): accept-ranges: bytes
I/flutter (24548): content-length: 6425
I/flutter (24548): x-frame-options: DENY
I/flutter (24548): x-content-type-options: nosniff
I/flutter (24548): expires: 0

Upvotes: 0

Views: 3233

Answers (1)

Abhijith
Abhijith

Reputation: 2327

I had this problem in but in android 11 or higher it is so hard to save the data into an external folder, because Android 11 + further enhances the platform, giving better protection to the app and user data on external storage so it is hard to save data, you save data in 12 it will save to app cache folder like above which won't be available to view in your file manager.

So what I did in the project is used a package called open_file It will open files with a default pdf viewer, in my case, it was google drive, so you can save it to a different folder but it should be done by the user.here is sample code,hope this helps,if not please look in to this answer

    void SaveData(){
        
        Directory? directory;
        directory = await getApplicationDocumentsDirectory();
        
        File saveFile = File(directory.path "nameofFile.pdf");
        
        var dio = Dio();
        String fileUrl = "download url";
        dio.options.headers['Content-Type'] = 'application/json';
        dio.options.headers['Authorization'] = 'Token if present';
    try {
        await dio.download(fileUrl, saveFile.path, onReceiveProgress: (received,total) {
    
        int progress = (((received / total) * 100).toInt());
    
        print(progress);
    
        final url = saveFile.path;
    
         OpenFile.open(url);
    
    
    });
        
    
     } on DioError catch (e) {
    
        EasyLoading.dismiss();
    
    }
        
}

Upvotes: 1

Related Questions