In Flutter How to get image path after selecting images using Multi Image Picker?

后端 未结 4 1403
执笔经年
执笔经年 2021-01-18 18:13

I want to get an image path from selected multiple images, I\'m using this link to select multiple images but I got assets, I want paths from selected multiple images becaus

相关标签:
4条回答
  • 2021-01-18 18:43

    Use multi_image_picker 4.7.14 library to pick Multiple Images. use below code you can send selected asset image as a file. `

    //Inside Widget Builder
    FlatButton(
                child: Image.asset(
                  "assets/images/camera.png",
                  color: Colors.grey,
                ),
                onPressed: loadAssets,
              ),
              
        SizedBox(
                      // height: SizeConfig.safeBlockHorizontal * 10,
                      height: MediaQuery.of(context).size.height / 2,
                      child: Column(
                        children: <Widget>[
                          Expanded(
                            child: buildGridView(),
                          ),
                        ],
                      ),
                    )

    List<File> fileImageArray = [];
      List<String> f = List();
      List<Asset> resultList = List<Asset>();
      List<Asset> images = List<Asset>();
      
      Future<void> loadAssets() async {
        try {
          resultList = await MultiImagePicker.pickImages(
            maxImages: 4,
            enableCamera: true,
            selectedAssets: images,
            cupertinoOptions: CupertinoOptions(takePhotoIcon: "chat"),
            materialOptions: MaterialOptions(
              actionBarColor: "#abcdef",
              actionBarTitle: "Example App",
              allViewTitle: "All Photos",
              useDetailsView: false,
              selectCircleStrokeColor: "#000000",
            ),
          );
        } on Exception catch (e) {
          error = e.toString();
        }
    
        if (!mounted) return;
    
        for (int i = 0; i < resultList.length; i++) {
          var path =
              await FlutterAbsolutePath.getAbsolutePath(resultList[i].identifier);
          print(path);
          f.add(File(path));
        }
    
        setState(() {
          images = resultList;
        });
    
        // return fileImageArray;
      }
    
    //image PreView
      Widget buildGridView() {
        return GridView.count(
          crossAxisCount: 4,
          children: List.generate(images.length, (index) {
            Asset asset = images[index];
            return AssetThumb(
              asset: asset,
              width: 50,
              height: 50,
            );
          }),
        );
      }

    API Call : while image uploading place use multipart file

    List<MultipartFile> newList = new List<MultipartFile>();
        
      Future<String> multiImagePostAPI() async {
        var request = http.MultipartRequest('POST', url);
        request.headers["Authorization"] = pref.getString("token");
        request.headers["Accept"] = "application/json";
        
         for (int i = 0; i < f.length; i++) {
          newList.add(await http.MultipartFile.fromPath('photo[]', f[i].path));
        }
        request.files.addAll(newList);
         Map<String, dynamic> data = Map<String, String>();
          data["user_id"] = user_id;
          data["project_id"] = pro_id;
          data["title"] = titleController.text;
    
          request.fields.addAll(data);
    
          var res = await request.send();
         
         if (res.statusCode == 200) {
          debugPrint("Status$res");
         }else {
          debugPrint("status : $res");
          }
          
         
         }

    0 讨论(0)
  • 2021-01-18 18:55

    I'm Using below Code to select multiple images by using file_picker: ^2.0.7 Library. Long press to select multiple image. Once Image Selected you can use f arr to display the images.

    List<File> f = List();
    
     RaisedButton(
                child: Text("Pick Image"),
                onPressed: () async {
                  FilePickerResult result = await FilePicker.platform.pickFiles(
                    allowMultiple: true,
                    type: FileType.custom,
                    allowedExtensions: ['jpg', 'png', 'jpeg'],
                  );
                  if (result != null) {
                    f = result.paths.map((path) => File(path)).toList();
                    setState(() {});
                    print(f);
                  }
                },
              ),

    Sample API Call For image upload and normal data. Image uploaded column should be arr ( photo[] ).

     List<MultipartFile> newList = new List<MultipartFile>();
    
    
    Future<String> ImageUpload() async {
    
    var request = http.MultipartRequest('POST', url);
     request.headers["Authorization"] = pref.getString("token");
        request.headers["Accept"] = "application/json";
       //Image Data
      for (int i = 0; i < f.length; i++) {
          newList.add(await http.MultipartFile.fromPath('photo[]', f[i].path));
        }
        request.files.addAll(newList);
        
        Map<String, dynamic> data = Map<String, String>();
        //normal data
        data["user_id"] = user_id;
        data["project_id"] = pro_id;
        
        request.fields.addAll(data);
        var res = await request.send();
        
        if (res.statusCode == 200) {
          debugPrint("Status${res}");
          }else {
          debugPrint("status code${res}");
          }
          
        }
        

    Try This You can select and upload multiple images easily. Thank you.
    
    0 讨论(0)
  • 2021-01-18 18:58

    You can also select multiple images using file_picker: ^1.5.0+2 library and easy to get path of selected images

    Future<int> getFilePath() async {
    try {
      files = await FilePicker.getMultiFile();
      if (files == '') {
        return 0;
      }
      else
      {
        setState(() {
          this._filePath = files;
          return 1;
        });
      }
    
    } on PlatformException catch (e) {
      print("Error while picking the file: " + e.toString());
    }
    

    }

    show selected images by using ListView Builder like this

                   ListView.builder(
                  scrollDirection: Axis.horizontal,
                  itemCount: _filePath.length,
                  itemBuilder: (context,c)
                  {
    
                    return Card(
                      child: Image.file(_filePath[c],
                        fit: BoxFit.fill,
                        width: 400,
                        height: 400,
    
                      ),
                    );
                  }
              ),
    
    0 讨论(0)
  • 2021-01-18 19:00
    Padding(
                padding: const EdgeInsets.all(18.0),
                child: InkWell(
                  child: Text(
                    'POST',
                    style: TextStyle(fontSize: 18.0),
                  ),
                  onTap: () async {
    
     List<MultipartFile> multipart = List<MultipartFile>();
    
                    for (int i = 0; i < images.length; i++) {
                      var path = await FlutterAbsolutePath.getAbsolutePath(images[i].identifier);
    
                    }   
    
                  },
                ),
              )
    
    0 讨论(0)
提交回复
热议问题