want to fetch bytes of selected file from device - flutter

So basically i want to select the files from my device and encrypt them with the help of bytes.
I am done with the selection part and have done that using file picker if anyone can help me how to get bytes of the file i have selected it would be really helpful.
here is my code to pick files from device
void selectFileFromDevice(d) async{
FilePickerResult filePickerResult = await FilePicker.platform.pickFiles(allowMultiple: true);
if(filePickerResult!=null){
List<io.File> files = filePickerResult.paths.map((path) => io.File(path)).toList();
}else{
print('user cancelled the picker');
}
}
the above code is working absolutely fine i just want to know how can get the bytes of my selected files.
Thank you

you can use the following code to get the bytes of your file
Uint8List bytes = await files[0].readAsBytes();

Related

Flutter How to pick an image and convert BASE64 string in web

Actually I'm very new in Flutter-Dart.
And I'm writing an web app. So I should pick images from file path in web. And I should convert the image to base64 code. because I will add the image to my PHP server with my php codes. PHP code is ready. but I don't know a lot of information about pick images and convert base64. Can anybody help me.
Add file_picker: ^4.3.0 to pubspec.yaml and try this:
void pickFile(){
FilePickerResult? result = await FilePicker.platform.pickFiles(
type: FileType.custom,
);
if (result != null) {
Uint8List? file = result.files.first.bytes!;
final x = base64Encode(file);
//do what you want with x.
}
}

resume downloading messes up the file

i'm trying to download a large file and be able to resume the downloading where it left off,
i'm currently using this code to achieve this
//downloadUntil is a large number (~10GB) so that if we don't specify
//our own number the http will automatically trim it to the file size.
downloadFile(String url, {int downloadFrom=0, int downloadUntil=99999999999 }) async {
var httpClient = http.Client();
var request = new http.Request('GET', Uri.parse(url));
//we will add Range to the header, downloadFrom will be zero
//if the file is being downloaded for the first time,
//and it will be a different number if we're resuming the download.
request.headers.addAll({'Range': 'bytes=$downloadFrom-$downloadUntil'});
var response = httpClient.send(request);
//create a RandomAccessFile object so that we can write the chunks to the file.
RandomAccessFile raf = await File(downloadPath).open(mode: FileMode.write);
//this variable will keep track of the downloaded bytes,
//we use it to offset the file when writing to it.
int downloaded = downloadFrom;
response.asStream().listen((http.StreamedResponse r) {
r.stream.listen((List<int> chunk) async {
//print the percentage
debugPrint('downloadPercentage: ${downloaded / r.contentLength * 100}');
//offsetting the file
raf.setPositionSync(downloaded);
//then write the downloaded chunk to the file
raf.writeFromSync(chunk);
//update the downloaded variable
downloaded += chunk.length;
}, onDone: () async {
debugPrint('download completed');
return;
});
});
}
the file works fine when for example i have a 150MB video file and download only 50MB by executing this code:-
downloadFile("https://commondatastorage.googleapis.com/gtv-videos-bucket/sample/BigBuckBunny.mp4", downloadUntil: 50000000//~50MB);
the video file works fine, i can watch the downloaded part, everything works as intended.
then i execute this code to download the remaining bytes:-
downloadFile("https://commondatastorage.googleapis.com/gtv-videos-bucket/sample/BigBuckBunny.mp4", downloadFrom: 50000000//~50MB);
then the video file doesn't work anymore, it gets unseekable stream,
i also tried to download the file by downloadFrom:49999900 and replace some of the downloaded bytes to avoid skipping any bytes,
also tried downloadFrom: 50000001 to avoid replacing any downloaded bytes, none of them worked.
what am i doing wrong here?
You are opening the file with FileMode.write which overwrites all the existing bytes saved by the previous download. Change it to FileMode.append and you are good to go.

flutter image picker reduce file size with provider and flutter_image_compress

I am using image picker to pick image from device(App) and after that stored that file in provider class like that.
File? _img;
get img=> _img;
void putbannerimg(File img) {
_img = img;
notifyListeners();
}
I found out that image picker does not compress png images, I tried compressing it with flutter_image_compress
compressFile() async {
final formservice = Provider.of<PostForm>(context, listen: false);
File file = formservice.bannerfile;
final result = await FlutterImageCompress.compressWithFile(
file.absolute.path,
quality: 54,
);
formservice.putbannerimg(File.fromRawPath(result!));
}
I tried this way And other multiple ways but getting different different errors I want to upload this file in firebase storage like this
var task = storageicon.putFile(formservice.iconfile);
please tell me where I am going wrong, without compress file all things are working fine
Edit: I found out that path should be a string how can I parse local code file in that
If you are using the "flutter_image_compress" package
You may have to use the compress function for files stored on the phone like this:
Future<File> testCompressAndGetFile(File file, String targetPath) async {
var result = await FlutterImageCompress.compressAndGetFile(
file.absolute.path, targetPath,
quality: 88,
rotate: 180,
);
print(file.lengthSync());
print(result.lengthSync());
return result;
}
"compressAndGetFile()" returns a file while "compressWithFile()" returns a Uint8List.
If i understand your last question right, you want to use an image built into your application by default.
For this, you have to open your "pubsepc.yaml", go to the "flutter:" mark and add "assets:" like so:
flutter:
assets:
- path
"path", in my example, describes a top level folder containing assets like pictures.
You can freely describe its name.

Api is returning media data in response.body in Flutter

I am using api in flutter that is returning media data so how to handle this.
ScreenShot of my code
Post Man screenshot
Thanks in advance for your precious time.
Save your response to temp file or application document directory and add Image.file widget to your project to show this downloaded file. to save file you can use path_provider package.
if(response.statusCode == 200) {
var bytes = await consolidateHttpClientResponseBytes(response);
filePath = '$dir/$fileName';
file = File(filePath);
await file.writeAsBytes(bytes);
}
else
filePath = 'Error code: '+response.statusCode.toString();
}
also check this stackoverflow question and answers.

How to fix Flutter stream exiting whenever i try to listen to it

In a flutter app, I'm trying to read a large csv file one line at a time by opening a stream on it. The issue is that when i try to listen to the stream the execution just skips over that code block and the program ends.
The file I'm opening is located in my assets folder and I've confirmed programmatically that it does exist before opening the stream. Changing the file the stream is opened on doesn't help, the same problem persists. I've also tried to change the way i listen to the stream, following different methods provided by Darts official documentation (that code is commented out) but the outcome is again the same. The assets have been declared in the pubspec.yaml. When i change the code to read the file as a String the program works perfectly but I want to use a stream because the file is so massive that creating a String object for it would take a large amount of time and memory.
void trainDigitsStream() async{
List<List<List>> filters = createRandomFilter(4, 4, 1, -1, 1);
List flattened= new List<double>();
File file = new File("assets/digit_train_data.csv");
if(file.existsSync())print("EXISTS!");
Stream<List<int>> stream = file.openRead();
Stream lines = utf8.decoder.bind(stream).transform(LineSplitter());
/*
try{
await for (var line in lines){
print(line);
}
print("file ended");
}catch(e){
print(e);
}
*/
lines.listen((data){//code exits here, execution never reaches next line
String line = data.toString();
List<List> instance = new List<List<int>>();
List x = new List<int>();
int i = 0;
line.split(',').forEach((d){
x.add(int.parse(d));
i++;
if(i == 28){
instance.add(x);
x = new List<int>();
i = 0;
}
});
List<List<List>> kernels = new List<List<List<double>>>();
List<List> pools = new List<List>();
filters.forEach((f){kernels.add(convo.applyFilter(instance, f, 0));});
kernels.forEach((k){pools.add(pool.maxPool(k, 2));});
pools.forEach((p){flattened.addAll(p);});
});
}
It's hard without further information, It would be better if you can post more information.
So I guess the problem should be , please check the following two steps.
1. Register the assets folder in pubspec.yaml
flutter:
assets:
- assets/digit_train_data.csv
2. You need to use rootBundle to access this csv file, reference document https://flutter.dev/docs/development/ui/assets-and-images
import 'dart:async' show Future;
import 'package:flutter/services.dart' show rootBundle;
Future<String> loadAsset() async {
return await rootBundle.loadString('assets/digit_train_data.csv');
}
similar question here Flutter - Read text file from assets