Flutter 多文件上传( FormData )

定义一个收集文件的数组

List<File> _imageFile = [];

点击上传文件按钮,底部弹出 (相机、图库)来选择

IconButton(
    icon: Icon(Icons.image),
    onPressed: () {
        showModalBottomSheet(
            context: context,
            builder: (BuildContext context) {
                return Column(
                    children: <Widget>[
                        ListTile(
                            leading: new Icon(Icons.photo_camera),
                            title: new Text("相机"),
                            onTap: () async {
                                File file = await ImagePicker.pickImage(source: ImageSource.camera);
                                _imageFile.add(file);
                                setState(() {});
                                Navigator.pop(context);
                            }
                        ),
                        ListTile(
                            leading: new Icon(Icons.photo_library),
                            title: new Text("图库"),
                            onTap: () async {
                                File file = await ImagePicker.pickImage(source: ImageSource.gallery);
                                _imageFile.add(file);
                                setState(() {});
                                Navigator.pop(context);
                            }
                        ),
                    ]
                );
            }
        )
    }
)

显示图片

Column(
    children: _imageFile.map((item) {
        return Image.file(
            File(item.path),
            fit: BoxFit.cover,
        );
    })
    
)

使用 FormData() 上传文件

FormData formData = FormData();
for(int i = 0; i < _imageFile.length; i++) {
    formData.files.add(
        MapEntry(
            "file",
            await MultipartFile.fromFile(
                _imageFile[i].path.toString()
            )
        )
    );
}

作者:Wuthier
链接:https://www.jianshu.com/p/8e3a0163879b
来源:简书
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。

Share