How to convert List<Asset> to List<File> in flutter - flutter

I am using this package to get mutliple images from gallery and it return a list of Asset, now I want to send it to server, I am use FormDate but there image path required.
Is there any other way to send Asset image to server?
how to convert List<Asset> to List<File>.
how to get image path from Asset
Or any other method to done this task(Choose mutliple images from storage and send them to server).
List<Asset> images = List<Asset>();
FormData imageFormData = FormData.fromMap({
"files": images.map((image) async {
return await MultipartFile.fromFile('assets/${image.name}', filename: image.name);
}).toList(),
});

Here is the solution.
List<Asset> images = List<Asset>();
List<MultipartFile> multipart = List<MultipartFile>();
for (int i = 0; i < images.length; i++) {
var path = await FlutterAbsolutePath.getAbsolutePath(images[i].identifier);
multipart.add(await MultipartFile.fromFile(path, filename: 'myfile.jpg'));
}
FormData imageFormData = FormData.fromMap({"files": multipart,});

Make use of flutter_absolute_path package.
add flutter_absolute_path: ^1.0.6 in pubsec.yaml

This will convert file path from this format : “content://media/external/images/media/5275”
To this format (absolute format)
"/storage/emulated/0/DCIM/Camera/IMG_00124.jpg”
Then make use of this method:
Future<List> imagePicker() async{
List<Asset> assetArray = [];
List <File> fileImageArray = [];
try {
assetArray = await MultiImagePicker.pickImages(
maxImages: 300,
enableCamera: true,
selectedAssets: assetArray ,
cupertinoOptions: CupertinoOptions(takePhotoIcon: "chat"),
materialOptions: MaterialOptions(
actionBarColor: "",
actionBarTitle: "ImagePicker",
allViewTitle: "All Photos",
useDetailsView: false,
selectCircleStrokeColor: "#000000",
),
);
}on Exception catch (e) {
print( e.toString());
}
assetArray.forEach((imageAsset) async {
final filePath = await FlutterAbsolutePath.getAbsolutePath(imageAsset.identifier);
File tempFile = File(filePath);
if (tempFile.existsSync()) {
fileImageArray.add(tempFile);
}
});
return fileImageArray;
}

I think you can read assets file as file before sending over as below:
File imageFile = File('yourAssetsUriPath.jpg');
yourAssetsUriPath is pointing to your assets folder by default, so you can simply put your filename in the path.
As for http post it, you can refer here

Related

Uploading multiple Images to firebase in flutter

I sucessfully Get to pick multiple images from gallery and decided to try uploading to firebase and as well retrieving the image URL. after calling the upload it requested a pass a parameter which i did but it gives an error "The argument type 'List' can't be assigned to the parameter type 'Asset" when i try to specify the index of the parameter i passed it only Saves that image with that particular index.
i also tried a for loop but still it saves only one image and return its url.
How do i get to Upload all the images
Below is how i load the images.
Future<void> loadAssets() async {
List<Asset> resultList = <Asset>[];
resultList = await MultiImagePicker.pickImages(
maxImages: 300,
enableCamera: true,
selectedAssets: images,
cupertinoOptions: const CupertinoOptions(takePhotoIcon: "chat"),
materialOptions: const MaterialOptions(
actionBarColor: "#abcdef",
actionBarTitle: "Example App",
allViewTitle: "All Photos",
selectCircleStrokeColor: "#000000",
));
if (!mounted) return;
setState(() {
images = resultList;
});
}
then i upload the image using the following snippet
Future UploadImage(Asset asset) async {
String fileName = popop;
ByteData byteData = await asset.getByteData();
List<int> imageData = byteData.buffer.asUint8List();
Reference ref = FirebaseStorage.instance.ref().child(fileName);
UploadTask uploadTask = ref.putData(Uint8List.fromList(imageData));
TaskSnapshot snapshot= await uploadTask;
String url= await snapshot.ref.getDownloadURL();
if (kDebugMode) {
print(url);
}
/// After this Update user Profile or add url to collection
return url;
}
used the below code to call/upload a single image out of the list
RaisedButton(
child: const Text("Save Image"),
onPressed: () => UploadImage(images[0]),
),
How to i get to upload all images.
i even tried the for loop below
for(int i=o; i<images.length;i++){
UploadImages(images[i]);
}
But only uploaded a single image
You can iterate over your images like this for example:
final fileNames = <String>[];
for (final image in images) {
final fileName = await uploadImage(image);
fileNames.add(fileName);
}
Not sure whether you really need to call getDownloadUrl() (depends on your use case), but this method creates a public and long-lived url.
If you just want to store a reference in Cloud Firestore for example, you can get the name / fullPath of the respective file from your TaskSnapshot in the uploadImage function as follows:
Future<String> UploadImage(Asset asset) async {
String fileName = popop;
ByteData byteData = await asset.getByteData();
List<int> imageData = byteData.buffer.asUint8List();
Reference ref = FirebaseStorage.instance.ref().child(fileName);
UploadTask uploadTask = ref.putData(Uint8List.fromList(imageData));
TaskSnapshot snapshot= await uploadTask;
// Assuming you are interested in the fullPath use snapshot.ref.fullPath
// For the name use snapshot.ref.name instead
return snapshot.ref.fullPath
}

upload file in flutter web by file_picker

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 :)

path directory in flutter using path_provider

In my app I am downloading a files from server. I need to save this files to downloads folder in mobile phone storage. Can this was possible using path_provider package in android ?
This might be a duplicate of this question.
Checkout this answer.
You might want to consider saving the files in your app directory of your app, as described in the official pub.dev docs of path_provider.
You can use Dio for downloading and downloads_path_provider_28 for getting download folder path collectively for this:
Future download(String url) async {
final Dio dio = Dio();
Directory? downloadsDirectory = await DownloadsPathProvider.downloadsDirectory; // "/storage/emulated/0/Download"
final savePath = downloadsDirectory?.path;
try {
Response response = await dio.get(
url,
onReceiveProgress: (received, total) {
if (total != -1) {
print((received / total * 100).toStringAsFixed(0) + "%");
}
},
options: Options(
responseType: ResponseType.bytes,
followRedirects: false,
validateStatus: (status) {
return status < 500;
}
),
);
print(response.headers);
File file = File(savePath);
var raf = file.openSync(mode: FileMode.write);
// response.data is List<int> type
raf.writeFromSync(response.data);
await raf.close();
} catch (e) {
print(e);
}
}

I am using the Flutter Plugin Image_picker to choose images so that I want to upload image after selected the image

this is my code
Future<File> _imageFile;
void _onImageButtonPressed(ImageSource source) async {
setState(() {
_imageFile = ImagePicker.pickImage(source: source);
});
}
I find this code in flutter documentation but its not work
var uri = Uri.parse("http://pub.dartlang.org/packages/create");
var request = new http.MultipartRequest("POST", url);
request.fields['user'] = 'nweiz#google.com';
request.files.add(new http.MultipartFile.fromFile(
'package',
new File('build/package.tar.gz'),
contentType: new MediaType('application', 'x-tar'));
request.send().then((response) {
if (response.statusCode == 200) print("Uploaded!");
});
I used file_picker library to pick files. you can use this for pick images as well.
Future getPdfAndUpload(int position) async {
File file = await FilePicker.getFile(
type: FileType.custom,
allowedExtensions: ['pdf','docx'], //here you can add any of extention what you need to pick
);
if(file != null) {
setState(() {
file1 = file; //file1 is a global variable which i created
});
}
}

Images doesn't show in gallery

In my application i need to download image from URL and after that show the image in gallery.I'm using flutter_downloader plugin ,
and this my functions to download
Future<String> _findLocalPath() async {
final directory = widget.platform == TargetPlatform.android
? await getExternalStorageDirectory()
: await getApplicationDocumentsDirectory();
return directory.path;
}
Future _downloadImg(String url) async {
_localPath = (await _findLocalPath()) + '/Download';
final savedDir = Directory(_localPath);
bool hasExisted = await savedDir.exists();
if (!hasExisted) {
savedDir.create();
}
FlutterDownloader.enqueue(
url: url,
savedDir: _localPath,
showNotification: true,
openFileFromNotification: true,
fileName: '${DateTime.now().millisecondsSinceEpoch}.jpg');
}
the image downloaded but doesn't show in gallery , so how can i make it visible in gallery?.
Edit You can use pacakage image_downloader to download image with process and save image with image_gallery_saver
package https://pub.dev/packages/image_downloader have progress callback
ImageDownloader.callback(onProgressUpdate: (String imageId, int progress) {
setState(() {
_progress = progress;
});
});
You can use package https://github.com/hui-z/image_gallery_saver to save image or video file in temp directory to gallery.
code snippet for save File
_saveVideo() async {
var appDocDir = await getTemporaryDirectory();
String savePath = appDocDir.path + "/temp.mp4";
await Dio().download("http://clips.vorwaerts-gmbh.de/big_buck_bunny.mp4",
savePath);
final result = await ImageGallerySaver.saveFile(savePath);
print(result);
}
You can also save image to gallery with this plugin' saveImage function
_save() async {
var response = await Dio().get("https://ss0.baidu.com/94o3dSag_xI4khGko9WTAnF6hhy/image/h%3D300/sign=a62e824376d98d1069d40a31113eb807/838ba61ea8d3fd1fc9c7b6853a4e251f94ca5f46.jpg", options: Options(responseType: ResponseType.bytes));
final result = await ImageGallerySaver.saveImage(Uint8List.fromList(response.data));
print(result);
}