0

I'm trying to force download a pdf file when the link is clicked. For some links, it works. But other pdf links, it just shows pdf in the browser. I'd appreciate if you could help! Thanks

Mitsuki
  • 58
  • 2
  • 6

1 Answers1

1

1st way

it's managed from the URL. I think. you can check this link. because that download URL contains some header based on that browser performing an action.

show file in browser:

Content-Type: application/pdf
Content-Disposition: inline; filename="filename.pdf"

download file in browser

Content-Type: application/pdf Content-Disposition: attachment;
filename="filename.pdf"

so basically you need to manage this in URL.

2nd way you can also directly download files from URL

Web download option

import 'dart:html' as html;
void downloadFile(String url) {
   html.AnchorElement anchorElement =  new html.AnchorElement(href: url);
   anchorElement.download = url;
   anchorElement.click();
}

If you want to Download and Save files from URL without external libraries. mobile platform

Future<String> downloadFile(String url, String fileName, String dir) async {
     HttpClient httpClient = new HttpClient();
     File file;
     String filePath = '';
     String myUrl = '';
            
   try {
          myUrl = url+'/'+fileName;
          var request = await httpClient.getUrl(Uri.parse(myUrl));
          var response = await request.close();
         if(response.statusCode == 200) {
                    var bytes = await consolidateHttpClientResponseBytes(response);
                    filePath = '$dir/$fileName';
                    file = File(filePath);
                    await file.writeAsBytes(bytes);
              } else
                    filePath = 'Error code:'+response.statusCode.toString();
            } catch(ex){
                  filePath = 'Can not fetch url';
      }
            
       return filePath;
}
Vishal Zaveri
  • 1,372
  • 2
  • 5
  • 12