Flutter How to download a file from an url without any third party library

Viewed 984

I have a download url of a file. Now I want to download the file and get the file as a File.

Now how can I do that? need help.

1 Answers

Well, you can use Dart s HttpClient class and The implementation will be something like this method given below.

import 'dart:io';
import 'package:flutter/foundation.dart';


  Future<File> _downloadFile(String url, String filename) async {
    var httpClient = new HttpClient();
    try{
      var request = await httpClient.getUrl(Uri.parse(url));
      var response = await request.close();
      var bytes = await consolidateHttpClientResponseBytes(response);
      final dir = await getTemporaryDirectory();//(await getApplicationDocumentsDirectory()).path;
      File file = new File('${dir.path}/$filename');
      await file.writeAsBytes(bytes);
      print('downloaded file path = ${file.path}');
      return file;
    }catch(error){
      print('pdf downloading error = $error');
      return File('');
    }

Related