how to read imported file flutter - flutter

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();

Related

Converting PlatformFile to File

I am using the package file_picker to select a PDF file from the device and uploading it to a remote server.
void capturarPDF() async{
FilePickerResult? result = await FilePicker.platform.pickFiles(
type: FileType.custom,
allowedExtensions: ['pdf'],
);
if(result == null) return;
PlatformFile file = result!.files.first ;
print("file ${file.path}");
_upload(file);
}
void _upload(File file) {
if (file == null) return;
setState(() {});
String base64Image = base64Encode(file.readAsBytesSync());
String fileName = file.path!.split("/").last;
String? mimeStr = lookupMimeType(file.path.toString());
var fileType = mimeStr!.split('/');
var tipo = "3";
http.post(Uri.parse(phpEndPoint), body: {
"image": base64Image,
"name": fileName,
"cod_sat": widget.codigo,
"tipo": tipo,
}).then((res) async {
setState(() {
});
}).catchError((err) {
print(err);
});
}
My issue is that at line _upload(file); I am getting the error:
The argument type 'PlatformFile' can't be assigned to the parameter type 'File'
Is there a way to convert a PlatformFile generated by the package file_picker to the type File needed to upload the file?
PlatformFile has a path reference to the file, you can take that path and set a File object with that path like this:
final path = file.path
_upload(File(path));

Delete file permanantly from list view in flutter

I list all pdf files from storage and now I want to delete multi-files in my flutter list . as well as from the device file manager. I am using this function but when I delete and restart the app the file comes again
This is the function I'm using to delete the list:
void deleteItems() {
var list = myMultiSelectController.selectedIndexes;
list.sort((b, a) => a.compareTo(b));
list.forEach((element) {
files.removeAt(element);
});
setState(() {
myMultiSelectController.set(files.length);
});
}
files.removeAt(element); Just removes file from the list. You need to actually delete file from device.
eg
Future<String> get _localPath async {
final directory = await getApplicationDocumentsDirectory();
return directory.path;
}
Future<File> get _localFile async {
final path = await _localPath;
print('path ${path}');
return File('$path/counter.txt');
}
Future<int> deleteFile() async {
try {
final file = await _localFile;
await file.delete();
} catch (e) {
return 0;
}
}
See more here from SO answer

Flutter App for encryption an audio for secure

I have a project with encrypt an audio for secure my data audio and when the user purchase they can play the audio, but until now didn't find how to do that. I found another way by converting the audio data into a string and then encrypting it, I found a code but it's incomplete so I'm still confused about using it.
import 'dart:io';
import 'dart:typed_data';
import 'package:file_picker/file_picker.dart';
import 'package:path_provider/path_provider.dart';
class MediaFile {
Future<String> get docPath async {
Directory appDocDir = await getApplicationDocumentsDirectory();
return appDocDir.path;
}
Future<Uint8List> get audioFileData async {
final String path = await docPath;
final String theFilePath = '$path/test.mp3';
final File theFile = new File(theFilePath);
if (await theFile.exists()) {
return await theFile.readAsBytes();
} else {
File file = await FilePicker.getFile();
return await file.readAsBytes();
}
}
Future<String> dataToString() async {
Uint8List data = await audioFileData;
return new String.fromCharCodes(data);
}
Future<File> saveMediaAsString(String fileName, String fileContent) async {
String path = await docPath;
Directory dataDir = new Directory('$path/data');
if (await dataDir.exists()) {
File file = new File('$path/data/$fileName');
return file.writeAsString(fileContent);
}
await dataDir.create();
File file = new File('$path/data/$fileName');
return file.writeAsString(fileContent);
}
Future<String> readFromStringMediaFile(String fileName) async {
String path = await docPath;
File file = new File('$path/data/$fileName');
return file.readAsString();
}
Uint8List stringToData(dataStr) {
List<int> list = dataStr.codeUnits;
return new Uint8List.fromList(list);
}
Future<File> createAudioFile(String fileName, Uint8List bytes) async {
String path = await docPath;
File file = new File('$path/$fileName');
return await file.writeAsBytes(bytes);
}
//here you can see how to use them
Future<File> testFile() async {
String dataStr = await dataToString();
File savedFile = await saveMediaAsString('codedFile', dataStr);
String contentSavedFile = await readFromStringMediaFile('codedFile');
Uint8List bytes = stringToData(contentSavedFile);
return await createAudioFile('test.mp3', bytes);
}
}

Make PlatformFile into File in Flutter using File Picker

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.

Weird behavior when adding Strings to a list

I am experiencing this weird behavior when loading assets from external storage, sometimes the path gets added to the list and most of the time the path is not added.
Here is my function, Am I missing something?
Future<List<String>> loadAssets() async {
List<String> loadedAssets = [];
loadedAssets.add('test');
try {
final Directory dir = await syspath.getExternalStorageDirectory();
dummyData.forEach((path) async {
final extPath =
path.substring(('assets/products_dummy_data/'.length));
final localPath='${dir.path}/$extPath}';
final file = File(localPath);
if (await file.exists()) {
await file.delete();
}
final data = await rootBundle.load(path);
var asUint8List =
data.buffer.asUint8List(data.offsetInBytes, data.lengthInBytes);
await file.create(
recursive: true,
);
await file.writeAsBytes(asUint8List);
if (await file.exists()) {
loadedAssets.add(localPath);
}
});
} catch (e, s) {
AppHelper.appLogger.e('Error while loading assets', e, s);
}
AppHelper.appLogger.i('loadedAssets.length ${loadedAssets.length}');
return loadedAssets;
}
But I always get the length as one, for the test element added
Problem Fixed after using await Future.forEach