Flutter 多文件上传( FormData )

Flutter 多文件上传( FormData )

1、定义一个收集文件的数组

List _imageFile = [];

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

IconButton(
	icon: Icon(Icons.image),
	onPressed: () {
		showModalBottomSheet(
			context: context,
			builder: (BuildContext context) {
				return Column(
					children: [
						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);
							}
						),
					]
				);
			}
		)
	}
)

3、显示图片

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

4、使用 FormData() 上传文件

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

你可能感兴趣的:(flutter,android)