Reputation: 3709
In my flutter project, I want to download some files from a url and save particularly in a folder named data. I have added Read and Write permission in AndroidManifest.xml file. I have also tried some solutions like the below link-
flutter - How to download asset when apps launched and used it
But none of them was effective for me. some of the solutions let me save the file in SD card but I only need to save the file in my data folder and read data from the file whenever I need.
Here's the picture where I exactly want to save my file-
So, I need a proper solution to download the file from the url and save it to this particular directory.
Upvotes: 2
Views: 5260
Reputation: 1621
As I understand it, you want to save any file from url in the data folder of the application and read it.
First you need to install the path_provider and http packages.
open terminal and run scripts:
flutter pub add path_provider
flutter pub add http
Let's add the files to the beginning of the file.
import 'dart:io';
import 'package:path/path.dart';
import 'package:path_provider/path_provider.dart';
import 'package:http/http.dart' show get;
Now let's write the download and save code:
Future<bool> yourMethodName(String downloadUrl) async {
var url = Uri.parse(downloadUrl);
var response = await get(url);
var documentDirectory = await getApplicationDocumentsDirectory();
// yourDirectoryName or assets...
var yourPath = "${documentDirectory.path}/yourDirectoryName";
var filePathAndName = '$yourPath/fileName.jpg';
await Directory(yourPath).create(recursive: true);
File yourFile = File(filePathAndName);
yourFile.writeAsBytesSync(response.bodyBytes);
return true;
}
Call from within any function
callFunction()async{
await yourMethodName('http://example.com/image.jpg'); // Or pdf,or etc.
}
There is a different approach for each file. If you give more detailed information, I can help you with the reading. For example I want to read picture or pdf.
If you have any questions don't hesitate to ask.
Upvotes: 0
Reputation: 9
https://pub.dev/packages/download_assets if you don't want to add assets at time of build try this package it download asset from server and store it in assets
Upvotes: 0