Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

flutter

dart

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.

  1. Is there any other way to send Asset image to server?

  2. how to convert List<Asset> to List<File>.

  3. 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(),
});
like image 480
Naeem Avatar asked Mar 02 '20 06:03

Naeem


3 Answers

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,});
like image 149
Abdul Haseeb Avatar answered Oct 09 '22 14:10

Abdul Haseeb


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

like image 35
xion Avatar answered Oct 09 '22 16:10

xion


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;

}

like image 2
Mohd Danish Khan Avatar answered Oct 09 '22 14:10

Mohd Danish Khan