Naeem
Naeem

Reputation: 514

How to convert List<Asset> to List<File> in 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.

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

Upvotes: 5

Views: 7431

Answers (3)

Abdul Haseeb
Abdul Haseeb

Reputation: 46

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

Upvotes: 3

Mohd Danish Khan
Mohd Danish Khan

Reputation: 1101

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;

}

Upvotes: 2

xion
xion

Reputation: 1259

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

Upvotes: 1

Related Questions