How to save and create files in internal device storage flutter - flutter

How can I save and create files in internal device storage in flutter? When I create file with getExternalStorageDirectory(), the file hasn't appeared in internal storage.
String fileExtension = name!.split('.').last;
String fileName =
name!.replaceAll('.${fileExtension}', '');
String? localPath = await _findLocalPath();
String completePath = '${localPath}/${fileName}.${fileExtension}';
logger.e(completePath);
io.File file = io.File(completePath);
await file.writeAsBytes(dataStore);
file.create();
Future<String?> _findLocalPath() async {
String? externalStorageDirPath;
if (io.Platform.isAndroid) {
final io.Directory? directory = await getExternalStorageDirectory();
externalStorageDirPath = directory!.path;
} else if (io.Platform.isIOS) {
externalStorageDirPath =
(await getApplicationDocumentsDirectory()).absolute.path;
}
final io.Directory savedDir = io.Directory(externalStorageDirPath!);
bool hasExisted = await savedDir.exists();
logger.e(hasExisted);
if (!hasExisted) {
logger.e('Create Folder');
savedDir.create();
}
return externalStorageDirPath;
}
Can anyone help me?

Try replacing the top block of code with this:
String fileExtension = name!.split('.').last;
String fileName =
name!.replaceAll('.${fileExtension}', '');
String? localPath = await _findLocalPath();
String completePath = '${localPath}/${fileName}.${fileExtension}';
logger.e(completePath);
io.File file = io.File(completePath);
//await file.writeAsBytes(dataStore);
//file.create();
var output = file.openWrite(mode: FileMode.writeOnlyAppend);
await for (final data in dataStore) {
output.add(data);
}
await output.close();

Related

Flutter http.dart get request to Infura Ipfs API does not download the files in the output directory

I have to download the files from ipfs inside a temporary Directory and load that files from that.
I'm using this one: https://docs.infura.io/infura/networks/ipfs/http-api-methods/get
and i referred to the param: output [Optional] - The path where the output should be stored.
Future<int> downloadItemIPFS(String hash,String localFolder) async {
String username = FlutterConfig.get('INFURA_PROJECT_ID');
String password = FlutterConfig.get('INFURA_API_SECRET');
String basicAuth = 'Basic ${base64.encode(utf8.encode("$username:$password"))}';
String tmpPath = await temporaryDirectoryPath;
Directory dir = await Directory("$tmpPath/$localFolder").create();
var url = Uri.https('ipfs.infura.io:5001','/api/v0/get',{'arg':hash ,'output': dir.path});
var request = http.MultipartRequest("POST", url);
request.headers['Authorization'] = basicAuth;
var response = await request.send();
var result = await http.Response.fromStream(response);
return result.statusCode;
}
Future<List<FileSystemEntity>> getDownloadedFiles(String folder) async {
String tmpPath = await temporaryDirectoryPath;
Directory dir = Directory("$tmpPath/$folder");
List<FileSystemEntity> out = dir.listSync();
return out;
}
the response returns 200 but the dyrectory seems empty
Edited code
Future<int> downloadItemIPFS(String hash,String localFolder) async {
String username = FlutterConfig.get('INFURA_PROJECT_ID');
String password = FlutterConfig.get('INFURA_API_SECRET');
String basicAuth = 'Basic ${base64.encode(utf8.encode("$username:$password"))}';
String tmpPath = await temporaryDirectoryPath;
Directory('$tmpPath/$localFolder').create();
var list = List<int>.generate(100, (i) => i)..shuffle();
List<int> names = list.take(5).toList();
String name = '';
for (int i = 0; i<names.length; i++) {
name += names[i].toString();
}
print("generated file named: $name");
var url = Uri.https('ipfs.infura.io:5001','/api/v0/get',{'arg':hash,'output': '$tmpPath/$localFolder'});
Response response = await http.post(url, headers: {HttpHeaders.authorizationHeader: basicAuth},);
print("Body content: ${response.body}");
await File("$tmpPath/$localFolder/$name.txt").writeAsBytes(response.bodyBytes);
return response.statusCode;
}
Future<List<FileSystemEntity>> getDownloadedFiles(String folder) async {
String tmpPath = await temporaryDirectoryPath;
Directory dir = Directory("$tmpPath/$folder/");
final List<FileSystemEntity> out = await dir.list().toList();
print("sono dentro getDownloadedFiles in helpefunctions.dart OUT: ${out.length}");
return out;
}
response format img

Image URL from firebase storage to firestore

this is how I upload images to firebase storage and get the Download URL in firebase Firestore. Everything works properly how ever I get the 1st URL but not the Second one.
Future<void> uploadImage2(image2) async {
setState(() {
isLoader2 = true;
});
final bytess = image2.readAsBytesSync();
var timeStamp = DateTime.now();
final metadata = firebase_storage.SettableMetadata(contentType: 'CarImage');
firebase_storage.UploadTask task = firebase_storage.FirebaseStorage.instance
.ref('Toyota-Images/$timeStamp/2.png')
.putData(bytess, metadata);
firebase_storage.TaskSnapshot downloadUrl2 = (await task);
String url = (await downloadUrl2.ref
.getDownloadURL()); //this is the url of uploaded image
imageUrl2 = url;
setState(() {
isLoader2 = false;
});
}
Future<void> uploadImage3(image3) async {
setState(() {
isLoader3 = true;
});
final bytess = image3.readAsBytesSync();
var timeStamp = DateTime.now();
final metadata = firebase_storage.SettableMetadata(contentType: 'CarImage');
firebase_storage.UploadTask task = firebase_storage.FirebaseStorage.instance
.ref('Toyota-Images/$timeStamp.png')
.putData(bytess, metadata);
firebase_storage.TaskSnapshot downloadUrl3 = (await task);
String url = (await downloadUrl3.ref
.getDownloadURL()); //this is the url of uploaded image
imageUrl3 = url;
setState(() {
isLoader3 = false;
});
}
You can upload image to firebase as below
First of all you need to add this plugin in pubspec.yaml
firebase_storage: ^8.0.0
import 'package:firebase_storage/firebase_storage.dart' as firebase_storage;
Future<void> uploadFile(File _image) async {
setState(() {
isLoader = true;
});
final bytess = _image.readAsBytesSync(); //"_image" is your selected image or any other which you need to upload
var timeStamp = DateTime.now();
final metadata = firebase_storage.SettableMetadata(contentType: 'image/jpeg');
firebase_storage.UploadTask task = firebase_storage.FirebaseStorage.instance
.ref('cover_photo/'+timeStamp.toString()+'insp_cover_photo.png').putData(bytess,metadata);
firebase_storage.TaskSnapshot downloadUrl = (await task);
String url = (await downloadUrl.ref.getDownloadURL()); //this is the url of uploaded image
setState(() {
isLoader = false;
});
}
Let me know if you have any questions
You can do it using firebase_storage.
you can get url by using this function.
Future<String> uploadFile(File _imageFile) async {
String fileName = DateTime.now().millisecondsSinceEpoch.toString();
Reference reference = FirebaseStorage.instance.ref().child(fileName);
UploadTask uploadTask = reference.putFile(_imageFile);
return uploadTask.then((TaskSnapshot storageTaskSnapshot) {
return storageTaskSnapshot.ref.getDownloadURL();
}, onError: (e) {
throw Exception(e.toString());
});
}

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

Print QR code using esc_pos_printer flutter

I'm using esc_pos_printer package which can print a receipt over network. I need two features
Save a qr/bar code in the gallery
Print said qr/bar code using the thermal printer/regular printer
For saving the qr code I did:
static Future<File> _saveBarCode(GlobalKey key, String productId) async {
print("save bar code");
RenderRepaintBoundary boundary =
key.currentContext!.findRenderObject() as RenderRepaintBoundary;
ui.Image image = await boundary.toImage();
ByteData? byteData = await image.toByteData(format: ui.ImageByteFormat.png);
Uint8List pngBytes = byteData!.buffer.asUint8List();
final tempPath = (await getTemporaryDirectory()).path;
final path = tempPath + "/" + productId + ".png";
File imgFile = File(path);
print(imgFile.path);
return imgFile.writeAsBytes(pngBytes);
}
and
static void save(GlobalKey key, String productId) async {
_saveBarCode(key, productId).then((value) async {
bool? saved = await GallerySaver.saveImage(value.path);
print("saved: $saved");
}).catchError((error) {
print(error);
});
}
But the printing part is giving me trouble:
void printOverNetwork(GlobalKey key, String productId) async {
const PaperSize paperSize = PaperSize.mm80;
final profile = await CapabilityProfile.load();
final printer = NetworkPrinter(paperSize, profile);
final PosPrintResult result =
await printer.connect('192.168.0.123', port: 9100);
_saveBarCode(key, productId).then((value) {
if (result == PosPrintResult.success) {
// print the qr/barcode
}
});
}
How can I solve the issue?

Flutter 'File' can't be assigned to 'XFile'

I have a function to save network image to local cache files, but I have a trouble when store the list file that I downloaded to List<XFile>. Here is my download function:
List<XFile>? imageFileList = [];
Future<File> downloadImage(url, filename) async {
var httpClient = HttpClient();
try {
var request = await httpClient.getUrl(Uri.parse(url));
var response = await request.close();
var bytes = await consolidateHttpClientResponseBytes(response);
final dir = await getTemporaryDirectory();
File file = File('${dir.path}/$filename');
await file.writeAsBytes(bytes);
print('downloaded file path = ${file.path}');
return file;
} catch (error) {
print('download error');
return File('');
}
}
is there any way so I can save the file to imageFileList as :
imageFileList!.add(file);
Convert the file to XFile:
XFile file = new XFile(file.path);
Change your list type:
from this:
List<XFile>? imageFileList = [];
to this:
List<File>? imageFileList = [];
final ImagePicker _picker = ImagePicker();
getImage() async {
var images = await _picker.pickMultiImage();
images!.forEach((image) {
setState(() {
_imageFileList!.add(File(image.path));
});
});
}