'How to upload Multiple Images to rest API in Flutter?
I am trying to upload upload multiple images to Rest API in flutter. the code i have written is given below:
final List<File> _image = [];
Future<Future<bool?>?> uploadImage(filePath, url) async {
if (_image.length > 0) {
for (var i = 0; i < _image.length; i++) {
print(_image.length);
var request =
http.MultipartRequest('POST', Uri.parse(url + _scanQrCode));
print(Uri.parse(url + _scanQrCode));
request.files.add(http.MultipartFile.fromBytes(
'picture',
File(_image[i].path).readAsBytesSync(),
filename: _image[i].path.split("/").last
));
var res = await request.send();
var responseData = await res.stream.toBytes();
var result = String.fromCharCodes(responseData);
print(_image[i].path);
}
_submitedSuccessfully(context);
}else{
return Fluttertoast.showToast(
msg: "Please Select atleast one image",
toastLength: Toast.LENGTH_SHORT,
gravity: ToastGravity.CENTER,
timeInSecForIosWeb: 1,
backgroundColor: Colors.red,
textColor: Colors.white,
fontSize: 16.0
);
}
}
The code is not working, the image is not getting uploaded. Please anyone help me to solve this problem
Solution 1:[1]
change your code to :
final List<File> _image = [];
Future<Future<bool?>?> uploadImage(String url) async {
// create multipart request
var request = http.MultipartRequest('POST', Uri.parse(url + _scanQrCode));
if (_image.length > 0) {
for (var i = 0; i < _image.length; i++) {
request.files.add(http.MultipartFile('picture',
File(_image[i].path).readAsBytes().asStream(), File(_image[i].path).lengthSync(),
filename: basename(_image[i].path.split("/").last)));
}
// send
var response = await request.send();
// listen for response
response.stream.transform(utf8.decoder).listen((value) {
debugPrint(value);
_submitedSuccessfully(context);
});
}
else{
return Fluttertoast.showToast(
msg: "Please Select atleast one image",
toastLength: Toast.LENGTH_SHORT,
gravity: ToastGravity.CENTER,
timeInSecForIosWeb: 1,
backgroundColor: Colors.red,
textColor: Colors.white,
fontSize: 16.0
);
}
}
Solution 2:[2]
this package ease your work, flutter_uploader:
final uploader = FlutterUploader();
final taskId = await uploader.enqueue(
url: "your upload link", //required: url to upload to
files: [FileItem(filename: filename, savedDir: savedDir, fieldname:"file")], // required: list of files that you want to upload
method: UploadMethod.POST, // HTTP method (POST or PUT or PATCH)
headers: {"apikey": "api_123456", "userkey": "userkey_123456"},
data: {"name": "john"}, // any data you want to send in upload request
showNotification: false, // send local notification (android only) for upload status
tag: "upload 1"); // unique tag for upload task
);
Solution 3:[3]
First you create to variable
List<File>? imageFileList = [];
List<dynamic>? _documents = [];
this method call when you pick image from gallery
pickMultipleImage(ImageSource source) async {
try {
final images = await picker.pickMultiImage(
maxWidth: 600, maxHeight: 600, imageQuality: 50);
if (images == null) return;
for (XFile image in images) {
var imagesTemporary = File(image.path);
imageFileList!.add(imagesTemporary);
}
} catch (e) {
}
}
this call when you pressed button for sending image to server
for(int i=0; i< _imageFileList!.length; i++ ){
var path = _imageFileList![i].path;
_documents!.add(await MultipartFile.fromFile(path,
filename: path.split('/').last));
}
var payload = dio.FromData.fromMap({ 'documents': _documents});
Dio() response = Dio.post(url, data: payload);
Solution 4:[4]
You can just use request.files.addAll
here a example :
Future uploadmultipleimage(List images) async {
var uri = Uri.parse("");
http.MultipartRequest request = new http.MultipartRequest('POST', uri);
request.headers[''] = '';
request.fields['user_id'] = '10';
request.fields['post_details'] = 'dfsfdsfsd';
//multipartFile = new http.MultipartFile("imagefile", stream, length, filename: basename(imageFile.path));
List<MultipartFile> newList = new List<MultipartFile>();
for (int i = 0; i < images.length; i++) {
File imageFile = File(images[i].toString());
var stream =
new http.ByteStream(DelegatingStream.typed(imageFile.openRead()));
var length = await imageFile.length();
var multipartFile = new http.MultipartFile("imagefile", stream, length,
filename: basename(imageFile.path));
newList.add(multipartFile);
}
request.files.addAll(newList);
var response = await request.send();
if (response.statusCode == 200) {
print("Image Uploaded");
} else {
print("Upload Failed");
}
response.stream.transform(utf8.decoder).listen((value) {
print(value);
});
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Meysam Asadi |
Solution 2 | Jim |
Solution 3 | Samu Chakraborty |
Solution 4 | rosner altamira |