How to Upload Image in Flutter & Save It in MySQL Database

How to Upload Image in Flutter & Save It in MySQL Database
Hello everyone, back again at porkaone. On this occasion we will learn how to upload images in Flutter and save them to a MySQL database. Curious?, let's follow in full below.

On this occasion, we will continue and refine the previous discussion, namely creating an image upload feature and saving it into the database. In this tutorial we will learn, http requests, image picker, grid view builder, snackbar, create back-ends, and learn other widget implementations.

How to Upload and Save Images in Flutter + MySQL and Php

1. First we will create the back-end part first. So please create a database with the name of practice and create a table in it with the name flutter_upload_images. Then follow the table structure as shown below.

Tabel Flutter Upload Images
Table of flutter_upload_images



2. Next, create a new folder in the htdocs folder with the name flutter_upload_image or with a free name. Then create a new file in it with the name create.php. Follow the script as below.
    
<?php $connection = new mysqli("localhost","root","","practice"); //get image name $image = $_FILES['image']['name']; //create date now $date = date('Y-m-d'); //make image path $imagePath = 'images/'.$image; $tmp_name = $_FILES['image']['tmp_name']; //move image to images folder move_uploaded_file($tmp_name, $imagePath); $result = mysqli_query($connection, "insert into flutter_upload_images set image='$image', date='$date'"); if($result){ echo json_encode([ 'message' => 'Data input successfully' ]); }else{ echo json_encode([ 'message' => 'Data Failed to input' ]); } ?>


3. Create a new file in the flutter_upload_image folder with the name list.php. Then follow the script as below.
   
<?php $connection = new mysqli("localhost","root","","practice"); $data = mysqli_query($connection, "select * from flutter_upload_images"); $data = mysqli_fetch_all($data, MYSQLI_ASSOC); echo json_encode($data);


4. Don't forget to create an images folder inside the flutter_upload_image folder. This folder serves to hold all the images later. So that the contents in the flutter_upload_image folder are the create.php file, the list.php file, and the images folder.

5. Next, create a new flutter project with the name flutter_upload_image. And in this tutorial I used the null safety version of Flutter.

6. After creating a new flutter project, then open the pubspec.yaml file. Then add the package image_picker: and package http: (no need to add the package version) Don't forget to press CTRL + S or save the file to download the required package. See the image below for the full details, (no need to add a package version).

Add Library



7. Next, open the main.dart file. Then replace the contents with the script below. And don't forget to replace each http://192.168.1.4/flutter_upload_image/ with the appropriate endpoints for each of your IP Address.
    
// ignore_for_file: unused_import, use_key_in_widget_constructors, unused_local_variable, prefer_const_literals_to_create_immutables, prefer_const_constructors, deprecated_member_use, sized_box_for_whitespace, avoid_print, unused_field, prefer_is_empty import 'dart:convert'; import 'dart:io'; import 'package:flutter/material.dart'; import 'package:image_picker/image_picker.dart'; import 'package:http/http.dart' as http; void main() => runApp(MaterialApp( home: Home(), debugShowCheckedModeBanner: false, )); class Home extends StatefulWidget { @override _HomeState createState() => _HomeState(); } class _HomeState extends State<Home> { XFile? image; List _images = []; final ImagePicker picker = ImagePicker(); //we can upload image from camera or from gallery based on parameter Future sendImage(ImageSource media) async { var img = await picker.pickImage(source: media); var uri = "http://192.168.1.4/latihan/flutter_upload_image/create.php"; var request = http.MultipartRequest('POST', Uri.parse(uri)); if(img != null){ var pic = await http.MultipartFile.fromPath("image", img.path); request.files.add(pic); await request.send().then((result) { http.Response.fromStream(result).then((response) { var message = jsonDecode(response.body); // show snackbar if input data successfully final snackBar = SnackBar(content: Text(message['message'])); ScaffoldMessenger.of(context).showSnackBar(snackBar); //get new list images getImageServer(); }); }).catchError((e) { print(e); }); } } Future getImageServer() async { try{ final response = await http.get(Uri.parse('http://192.168.1.4/latihan/flutter_upload_image/list.php')); if(response.statusCode == 200){ final data = jsonDecode(response.body); setState(() { _images = data; }); } }catch(e){ print(e); } } @override void initState() { // ignore: todo // TODO: implement initState super.initState(); getImageServer(); } //show popup dialog void myAlert() { showDialog( context: context, builder: (BuildContext context) { return AlertDialog( shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(8)), title: Text('Please choose media to select'), content: Container( height: MediaQuery.of(context).size.height / 6, child: Column( children: [ ElevatedButton( //if user click this button, user can upload image from gallery onPressed: () { Navigator.pop(context); sendImage(ImageSource.gallery); }, child: Row( children: [ Icon(Icons.image), Text('From Gallery'), ], ), ), ElevatedButton( //if user click this button. user can upload image from camera onPressed: () { Navigator.pop(context); sendImage(ImageSource.camera); }, child: Row( children: [ Icon(Icons.camera), Text('From Camera'), ], ), ), ], ), ), ); }); } @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: Text('Upload Image'), actions: [ IconButton( onPressed: () => myAlert(), icon: Icon(Icons.upload), ) ], ), body: _images.length != 0 ? GridView.builder( gridDelegate: SliverGridDelegateWithFixedCrossAxisCount( crossAxisCount: 2 ), itemCount: _images.length, itemBuilder: (_, index){ return Padding( padding: EdgeInsets.all(10), child: Image( image: NetworkImage('http://192.168.1.4/latihan/flutter_upload_image/images/'+_images[index]['image']), fit: BoxFit.cover, ), ); } ) : Center(child: Text("No Image"),) ); } }

8. Ok, we have gone through all the steps, it's time to do a trial. Please run the emulator and run the project we just finished creating. If successful, it will look like the image below.
Final Result




Ok, great!, now you can make the image upload feature into the database in flutter + mysql + Php. Hopefully it's useful, if something is unclear or has difficulty, please ask directly in the comments column. That is all and thank you.

Post a Comment

0 Comments