Reputation: 461
I have been searching for a long time about how to enable users to select a group of images and upload them to the database through the image_picker.I was able to find my request in the following topic: enter link description here
And other similar topics on the site.
I tried to upload images to the database through the http package and php file. The code works and the attempt is successful, but the problem is that only one image is uploaded. How to solve this problem I need to upload all the images at once.
Code:
void main() {
runApp(
MyApp(),
);
}
class MyApp extends StatelessWidget {
// This widget is the root of your application.
@override
Widget build(BuildContext context) {
return MaterialApp(
title: '',
theme: ThemeData(
primarySwatch: Colors.blue,
visualDensity: VisualDensity.adaptivePlatformDensity,
),
home: PickImages(),
);
}
}
class PickImages extends StatefulWidget {
@override
_PickImagesState createState() => _PickImagesState();
}
class _PickImagesState extends State<PickImages> {
static final String uploadEndPoint = 'https://****************.php';
List<Object> images = List<Object>();
Future<File> _imageFile;
bool _isVisible = false;
String base64Image;
Future _onAddImageClick(int index, int type) async {
if (images != null)
setState(() {
// ignore: deprecated_member_use
_imageFile = ImagePicker.pickImage(
source: type == 1 ? ImageSource.camera : ImageSource.gallery,
imageQuality: 50,
);
getFileImage(index);
});
}
void getFileImage(int index) async {
_imageFile.then((file) async {
setState(() {
ImageUploadModel imageUpload = new ImageUploadModel();
imageUpload.imageFile = file;
images.replaceRange(index, index + 1, [imageUpload]);
});
});
}
void showImageBox() {
setState(() {
_isVisible = !_isVisible;
});
}
@override
void initState() {
super.initState();
setState(() {
images.add("Add Image");
images.add("Add Image");
images.add("Add Image");
images.add("Add Image");
images.add("Add Image");
images.add("Add Image");
});
}
startUpload() {
String NameImage = DateTime.now().millisecondsSinceEpoch.toString();
{
http.post(uploadEndPoint, body: {
"image": base64Image,
"NameImage": NameImage,
}).then((result) {
if (result.statusCode == 200) {
print('dddddddddddddddd ${result.statusCode}');
} else {
}
}).catchError((error) {
});
}
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Post Images'),
),
body: Column(
children: <Widget>[
Container(
//padding: EdgeInsets.only(right: 5),
child: Card(
elevation: 5,
child: ListTile(
trailing: Icon(Icons.attachment),
title: Text('Attachments'),
onTap: () {
showImageBox();
},
),
),
),
Visibility(
visible: _isVisible,
child: Padding(
padding: const EdgeInsets.only(top: 5.0, right: 5.0),
child: GridView.count(
shrinkWrap: true,
crossAxisCount: 3,
childAspectRatio: 1,
children: List.generate(images.length, (index) {
if (images[index] is ImageUploadModel) {
ImageUploadModel uploadModel = images[index];
//base64 image
List<int> imageBytes = uploadModel.imageFile.readAsBytesSync();
// base64Image = base64Encode(snapshot.data.readAsBytesSync());
base64Image = base64Encode(imageBytes); //'base64Image' holds the base64 image string
return Card(
clipBehavior: Clip.antiAlias,
child: Stack(
children: <Widget>[
Image.file(
uploadModel.imageFile,
fit: BoxFit.cover,
width: 300,
height: 300,
),
Positioned(
right: 5,
top: 5,
child: InkWell(
child: Icon(
Icons.remove_circle,
size: 20,
color: Colors.red,
),
onTap: () {
setState(() {
images.replaceRange(
index, index + 1, ['Add Image']);
});
},
),
),
],
),
);
} else {
return Card(
child: IconButton(
icon: Icon(Icons.camera_alt),
onPressed: () {
showModalBottomSheet(
context: context,
builder: (BuildContext context) {
return SafeArea(
child: Container(
child: new Wrap(
children: <Widget>[
new ListTile(
leading: new Icon(Icons.photo_camera),
title: new Text('Camera'),
onTap: () {
_onAddImageClick(index, 1);
Navigator.of(context).pop();
},
),
new ListTile(
leading:
new Icon(Icons.photo_library),
title: new Text('Gallery'),
onTap: () {
_onAddImageClick(index, 2);
Navigator.of(context).pop();
}),
],
),
),
);
},
);
},
),
);
}
}),
),
),
),
RaisedButton(
child: Text('send'),
onPressed: () {
startUpload();
},
),
],
),
);
}
}
class ImageUploadModel {
File imageFile;
ImageUploadModel({
this.imageFile,
});
}
<?php
$image = $_POST['image'];
$NameImage = $_POST['NameImage'];
include 'connt.php';
$path = "ImageCat/$NameImage.png";
$actualpath = "https://*****.com/*****/$path";
$sql = "INSERT INTO Cate (image) VALUES (?)";
$stmt = $con->prepare($sql);
$stmt->bind_param("s",$actualpath);
$stmt->execute();
$result = $stmt->get_result();
// if(mysqli_query($conn,$sql)){
file_put_contents($path,base64_decode($image));
echo "Successfully Uploaded";
// }
$stmt->close();
?>
Upvotes: 1
Views: 644
Reputation: 980
You can use HTTP
and MultipartFile
try {
var request = http.MultipartRequest(
"POST", Uri.parse("url"));
var photo1 = await http.MultipartFile.fromPath("photo1", _imageFile1.path);
var photo2 = await http.MultipartFile.fromPath("photo2", _imageFile2.path);
request.files.add(photo1);
request.files.add(photo2);
request.fields["additional_data"] = "data";
var response = await request.send();
response.stream.asBroadcastStream();
if (response.statusCode == 200) {
response.stream.transform(utf8.decoder).listen((value) async {
Map<String, dynamic> result = json.decode(value);
print(result);
});
} else {
print("error");
}
} catch (e) {
print(e);
}
Upvotes: 1