I am working on the app and for that, I need to get all files from storage it can be mp3,img pdf or anything. I followed a tutorial and they worked on flutter_file_manager. and this package is discontinued
You can use file_picker package instead. Moreover, you may need to use the path_provider package along with the file_picker package. Complete documentation and examples can be found on the pub pages of the mentioned packages.
Here are some code samples:
To pick a single file:
FilePickerResult? result = await FilePicker.platform.pickFiles();
if (result != null) {
File file = File(result.files.single.path);
} else {
// User canceled the picker
}
To pick multiple files:
FilePickerResult? result = await FilePicker.platform.pickFiles(allowMultiple: true);
if (result != null) {
List<File> files = result.paths.map((path) => File(path)).toList();
} else {
// User canceled the picker
}
To pick multiple files with Extensions filters:
FilePickerResult? result = await FilePicker.platform.pickFiles(
type: FileType.custom,
allowedExtensions: ['jpg', 'pdf', 'doc'],
);
To pick a directory:
String? selectedDirectory = await FilePicker.platform.getDirectoryPath();
if (selectedDirectory == null) {
// User canceled the picker
}
The usage for path_provider package:
Directory tempDir = await getTemporaryDirectory();
String tempPath = tempDir.path;
Directory appDocDir = await getApplicationDocumentsDirectory();
String appDocPath = appDocDir.path;
Related
I've been building an ios app and in it, it'll download a bunch of pdf from an API and save it to the local storage using the path_provider package in flutter:
This is the code I use to fetch the path:
Future<String> get localPath async {
final directory = await getApplicationDocumentsDirectory();
currentDir.value = directory.path;
return directory.path;}
And this is how I save it to the device:
Future<void> saveFilesToLocal(String url, String fileName) async {
try {
final path = await localPath;
final file = File('$path/$fileName');
if (await file.exists() == false) {
final response = await Dio().get(url,
options: Options(
responseType: ResponseType.bytes,
followRedirects: false,
receiveTimeout: 0));
final raf = file.openSync(mode: FileMode.write);
raf.writeFromSync(response.data);
await raf.close();
} else {
print("file already exists");
}
} catch (e) {
print('error: $e');
}
}
After I download and save the files to the storage, it'll be displayed as a gridview in the home page. To fetch that list of files I use this:
List<FileSystemEntity> files = [];
Future<void> getFilesList() async {
files.clear();
final path = await localPath;
Directory dir = Directory('$path');
files =
dir.listSync(recursive: true, followLinks: false);
update();
}
And all of this works fine in the ios device. But the current issue I'm facing while trying to run it on web is:
The package path_provider is not available for flutter web. I've been asked to create it as a web app too and I can't find an alternative for it. While looking for one I saw a post saying flutter web won't allow access to a device's local storage like that so it's not possible. Is it true? Is there a workaround? If it's about security, the app will only be run on specific devices. It won't be given to the public.
I am working on an app that should manage downloaded files.
For now I am able to download a file on both platforms, but I would need to know how can I get the downloaded files from the device.
This is the code used to download a file from Internet.
Future<void> downloadFile() async {
bool downloading = false;
var progressString = "";
final imgUrl = "https://flutter.github.io/assets-for-api-docs/assets/videos/butterfly.mp4";
Dio dio = Dio();
try {
var dir = await getApplicationDocumentsDirectory();
print("path ${dir.path}");
await dio.download(imgUrl, "${dir.path}/demo.mp4",
onReceiveProgress: (rec, total) {
print("Rec: $rec , Total: $total");
downloading = true;
progressString = ((rec / total) * 100).toStringAsFixed(0) + "%";
});
} catch (e) {
print(e);
}
downloading = false;
progressString = "Completed";
print("Download completed");
}
The path print output for Android is:
path /data/user/0/red.faro.labelconciergeflutter/app_flutter
The path print output for iOS is:
path /var/mobile/Containers/Data/Application/9CFDC9E3-D9A9-4594-901E-427D44E48EB9/Documents
What I need is to know how can an app user access the downloaded files when the app is closed or there is no internet connection to open the file from the original URL?
For getting files from the device you may use file_picker package.
FilePickerResult? result = await FilePicker.platform.pickFiles();
if (result != null) {
File file = File(result.files.single.path);
} else {
// User canceled the picker
}
You also can use the File class from the dart:io library.
Future<File> get _localFile async {
final path = await _localPath;
return File('$path/counter.txt');
}
If your goal is to access commonly used locations on the device’s file system you can use the path_provider plugin.
Directory tempDir = await getTemporaryDirectory();
String tempPath = tempDir.path;
Directory appDocDir = await getApplicationDocumentsDirectory();
String appDocPath = appDocDir.path
i use file_picker: ^4.2.0 show package for my application.
when i get web release as html, get some Error.
error: path always null in web release
my code to get file:
Future getFile() async {
FilePickerResult? result = await FilePicker.platform.pickFiles(
withReadStream: true,
type: FileType.custom,
allowedExtensions: ['png', 'jpeg', 'jpg', 'pdf'],
);
if (result != null) {
PlatformFile file = result.files.single;
setState(() {
_file = File(file.path.toString());
_filePath = file.path;
});
_uploadFile();
} else {
// file not choose
}
}
i use https://pub.dev/packages/file_picker but in flutter web path not suppor;
you should to use bytes;
i save file bytes in var _fileBytes and use in request;
var request = http.MultipartRequest('POST', Uri.parse('https://.....com'));
request.headers.addAll(headers);
request.files.add(
http.MultipartFile.fromBytes(
'image',
await ConvertFileToCast(_fileBytes),
filename: fileName,
contentType: MediaType('*', '*')
)
);
request.fields.addAll(fields);
var response = await request.send();
function ConvertFileToCast:
ConvertFileToCast(data){
List<int> list = data.cast();
return list;
}
it`s work for me :)
I am using the File Picker Plugin to choose a file from a device. The file is chosen in the datatype of a PlatformFile, but I want to send the file to Firebase Storage and I need a regular File for that. How can I convert the PlatformFile into a File so that I can send it to Firebase Storage? Here is the code:
PlatformFile pdf;
final GlobalKey<FormState> _formKey = GlobalKey<FormState>();
void _trySubmit() async {
final isValid = _formKey.currentState.validate();
if (isValid) {
_formKey.currentState.save();
final ref = FirebaseStorage.instance
.ref()
.child('article_pdf')
.child(title + '-' + author + '.pdf');
await ref.putFile(pdf).onComplete; // This throws an error saying that The argument type 'PlatformFile' can't be assigned to the parameter type 'File'
}
}
void _pickFile() async {
FilePickerResult result = await FilePicker.platform.pickFiles(
type: FileType.custom,
allowedExtensions: ['pdf'],
);
if (result != null) {
pdf = result.files.first;
}
}
Try this:
PlatformFile pdf;
final File fileForFirebase = File(pdf.path);
Happy coding! :)
If you're on a web app, you can post image files to Firestore with flutter_file_picker: (Taken from the FAQ page): https://github.com/miguelpruivo/flutter_file_picker/wiki/FAQ
// get file
final result = await FilePicker.platform.pickFiles(type: FileType.any, allowMultiple:
false);
if (result.files.first != null){
var fileBytes = result.files.first.bytes;
var fileName = result.files.first.name;
// upload file
await FirebaseStorage.instance.ref('uploads/$fileName').putData(fileBytes);
}
This works
File(platformFile.name)
Just be sure not duplicates in the file names in your logic.
so i have a function pickFile() :
Future pickFile() async {
FilePickerResult result = await FilePicker.platform.pickFiles(
type: FileType.custom,
allowedExtensions: ['txt'],
);
if (result != null) {
setState(() {
importfile = File(result.files.single.path);
});
}
}
i have acces to documentsdirectory with :
Future<String> get _localPath async {
final directory = await getApplicationDocumentsDirectory();
return directory.path;
}
but i don't know how to put the choosen file into my "importfile" variable :
File importfile;
i know right know i get the path to the file, but how to i actually get the txt content?
You can call readAsString method on file object. There are other methods like readAsStringSync, readAsLines, readAsLinesSync and openRead, those can be used as well.
File importedFile = File('some-file-path.txt');
String fileContent = await importedFile.readAsString();