close

How To Download File From URL And Save in Local Storage In Flutter

Hello Guys How Are you all? Hope You all are fine. Often when we are working with audio, video, and large files we are forced to save the file in the local storage and to access them offline. we are forced to download the file in the local store. So here I am sharing How To Download File From URL And Save in Local Storage In Flutter. Let’s Start This Article without wasting your time.

Method 1

In This Tutorial, We are going to use Flutter Plugin flutter_downloader Which is provided by Flutter Community itself.

  • Add this to your package’s pubspec.yaml file:
dependencies:
  flutter_downloader: ^1.5.2
  • Install it. You can install packages from the command line:
flutter pub get
  • If You Are Using iOS then Follow this iOS integration.
  • If you are using Android then Follow This Android integration.
  • Don’t Forget this integration Process .unless you have to face some errors.
  • Yow just use below method to download file.
  void _requestDownload(Stringt link) async {
    final taskId = await FlutterDownloader.enqueue(
        url: 'your download link',
        savedDir: 'the path of directory where you want to save downloaded files',
        showNotification: true, // show download progress in status bar (for Android)
        openFileFromNotification: true, // click on notification to open downloaded file (for Android)
     );
  }
  • Then call _requestDownload method with URL. Just Like below.
onTap: () {
   _requestDownload('your_donwload_link');
}

That’s It. You can Also Cancel Download, Pause Download, Resume Download And Retry Download With Following Lines Of Code.

  void _cancelDownload(_TaskInfo task) async {
    await FlutterDownloader.cancel(taskId: task.taskId);
  }

  void _pauseDownload(_TaskInfo task) async {
    await FlutterDownloader.pause(taskId: task.taskId);
  }

  void _resumeDownload(_TaskInfo task) async {
    String newTaskId = await FlutterDownloader.resume(taskId: task.taskId);
    task.taskId = newTaskId;
  }

  void _retryDownload(_TaskInfo task) async {
    String newTaskId = await FlutterDownloader.retry(taskId: task.taskId);
    task.taskId = newTaskId;
  }

For Android do not forgetto add these lines in the manifest file, otherwise it will not work on real device after build apk:

<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

Method 2

If you want to download and save files from URL without external libraries, you can use this code. It works for me.

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;
      }
  1. How to download mp3 file from URL and save to phone local storage in flutter ?

    To Download mp3 file from URL and save to phone local storage we need to use flutter_downloader package. to download any file from URL we need to use this plugin. Just Follow method 1 tutorial.

  2. How to download pdf from URL and save to phones local storage in flutter ?

    To download pdf from URL and save to phone storage in flutter we need to use flutter_downloader package. this is flutter community's official plugin.

  3. How to Download file in flutter ?

    Download file in flutter we have to use above method 1 tutorial. We are just going to use flutter_downloader package to download file from url.

  4. How to download file to phone download directory in flutter ?

    You Just Have to use files_utils and path_provider plugins to get specific path permission and then you can use dio OR flutter_downloder plugin to download files. see the example below.

  5. How to download a file and store it in downloads folder using Flutter ?

    To download the file and store it in the download folder using flutter we need to use files_utils and path_provider Plugin in our App. This will provide us to store files into our sdcard/downloads folder and then we can use flutter_downloader OR dio plugin to download file and then we can save it in our specific path.

  6. How to Download file From URL and save to phone storage in flutter ?

    To download a file from the URL and save it to phone storage in flutter we need to use the flutter_downloader package. This is the flutter community official's Plugin.

How to Download file From URL and save to phone storage in flutter ?

User can try with the available plugin flutter_downloader like below:

final taskId = await FlutterDownloader.enqueue(
  url: 'your download link',
  savedDir: 'the path of directory where you want to save downloaded files',
  showNotification: true, // show download progress in status bar (for Android)
  openFileFromNotification: true, // click on notification to open downloaded file (for Android)
);

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

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;
      }

For Android do not forget to add these lines in the manifest file, otherwise, it will not work on the real device after build apk.

Users need to declare permission in an AndroidManifest.xml file using the below code snippet

<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

How to download a file and store it in downloads folder using Flutter ?

  • Add These Dependency in your pubspec.yaml file.
  dio: ^3.0.0
  path_provider: ^1.3.0
  simple_permissions: ^0.1.9
  file_utils: ^0.1.3
  • You required to add permissons on android mainfest file.
  <uses-permission android:name="android.permission.INTERNET"/>
  <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
  <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
  • Here Is Sample Code to Download File and Save them into downloads folder.
  import 'dart:io';
  import 'package:flutter/material.dart';
  import 'package:dio/dio.dart';
  import 'package:path_provider/path_provider.dart';
  import 'dart:async';
  import 'package:simple_permissions/simple_permissions.dart';
  import 'package:file_utils/file_utils.dart';
  import 'dart:math';

  void main() => runApp(Downloader());

  class Downloader extends StatelessWidget {
    @override
    Widget build(BuildContext context) => MaterialApp(
          title: "File Downloader",
          debugShowCheckedModeBanner: false,
          home: FileDownloader(),
          theme: ThemeData(primarySwatch: Colors.blue),
        );
  }

  class FileDownloader extends StatefulWidget {
    @override
    _FileDownloaderState createState() => _FileDownloaderState();
  }

  class _FileDownloaderState extends State<FileDownloader> {

    final imgUrl = "https://images6.alphacoders.com/683/thumb-1920-683023.jpg";
    bool downloading = false;
    var progress = "";
    var path = "No Data";
    var platformVersion = "Unknown";
    Permission permission1 = Permission.WriteExternalStorage;
    var _onPressed;
    static final Random random = Random();
    Directory externalDir;

    @override
    void initState() {
      super.initState();
      downloadFile();
    }


    Future<void> downloadFile() async {
      Dio dio = Dio();
      bool checkPermission1 =
          await SimplePermissions.checkPermission(permission1);
      // print(checkPermission1);
      if (checkPermission1 == false) {
        await SimplePermissions.requestPermission(permission1);
        checkPermission1 = await SimplePermissions.checkPermission(permission1);
      }
      if (checkPermission1 == true) {
        String dirloc = "";
        if (Platform.isAndroid) {
          dirloc = "/sdcard/download/";
        } else {
          dirloc = (await getApplicationDocumentsDirectory()).path;
        }

        var randid = random.nextInt(10000);

        try {
          FileUtils.mkdir([dirloc]);
          await dio.download(imgUrl, dirloc + randid.toString() + ".jpg",
              onReceiveProgress: (receivedBytes, totalBytes) {
            setState(() {
              downloading = true;
              progress =
                  ((receivedBytes / totalBytes) * 100).toStringAsFixed(0) + "%";
            });
          });
        } catch (e) {
          print(e);
        }

        setState(() {
          downloading = false;
          progress = "Download Completed.";
          path = dirloc + randid.toString() + ".jpg";
        });
      } else {
        setState(() {
          progress = "Permission Denied!";
          _onPressed = () {
            downloadFile();
          };
        });
      }
    }

    @override
    Widget build(BuildContext context) => Scaffold(
        appBar: AppBar(
          title: Text('File Downloader'),
        ),
        body: Center(
            child: downloading
                ? Container(
                    height: 120.0,
                    width: 200.0,
                    child: Card(
                      color: Colors.black,
                      child: Column(
                        mainAxisAlignment: MainAxisAlignment.center,
                        children: <Widget>[
                          CircularProgressIndicator(),
                          SizedBox(
                            height: 10.0,
                          ),
                          Text(
                            'Downloading File: $progress',
                            style: TextStyle(color: Colors.white),
                          ),
                        ],
                      ),
                    ),
                  )
                : Column(
                    mainAxisAlignment: MainAxisAlignment.center,
                    children: <Widget>[
                      Text(path),
                      MaterialButton(
                        child: Text('Request Permission Again.'),
                        onPressed: _onPressed,
                        disabledColor: Colors.blueGrey,
                        color: Colors.pink,
                        textColor: Colors.white,
                        height: 40.0,
                        minWidth: 100.0,
                      ),
                    ],
                  )));
  }

How to download file to phone download directory in flutter ?

Just Follow the Above tutorial for How to download files to the phone download directory in flutter? Both Are The Same and you still have an issue then comment below we will help you.

How to Download file in flutter ?

Just Follow the Method 1 tutorial for How to Download files in flutter ?? Both Are The Same and you still have an issue then comment below we will help you.

How to download pdf from URL and save to phones local storage in flutter ?

Just Follow the Method 1 tutorial for How to download pdf from URL and save to phones local storage in flutter? Both Are The Same and you still have an issue then comment below we will help you. To download any file from the URL we just need to use the Method 1 tutorial.

How to download mp3 file from URL and save to phone local storage in flutter ?

Just Follow the Method 1 tutorial for How to download mp3 file from URL and save to phone local storage in flutter? Both Are The Same and you still have an issue then comment below we will help you. To download any file from the URL we just need to use the Method 1 tutorial.

So it’s all About Download File From URL And Save in Local Storage In Flutter ?. Hope this tutorial helped you a lot. Comment below Your thoughts and your queries. And Also Comment on your suggestion here.

Also Read

Leave a Comment

%d bloggers like this: