Flutter #105: How to upload Image with data to Server | Flutter Http Post Request | PHP REST API


Flutter #105: How to upload Image with data to Server | Flutter Http Post Request | PHP REST API

How to upload Image with data to Server | Flutter Http Post Request | PHP REST API. Copy and paste the below code as per your requirements.

birddata.php

<?php 
$db = mysqli_connect('localhost','root','','userdata');
if(!$db)
{
    echo "Database connection failed";
}
$return["error"] = false;
$return["msg"] = "";
if(isset($_POST['image']) && isset($_POST['description']) && isset($_POST['name']))
{
    $base64_string = $_POST['image'];
    $name = $_POST["name"];
    $description = $_POST["description"];
    $randomstring = uniqid('bird');
    $outputfile = "uploads/{$randomstring}.jpg";
    $filehandler = fopen($outputfile, 'wb');
    fwrite($filehandler, base64_decode($base64_string));
    fclose($filehandler);
    $insert = "INSERT INTO birds(name,description,image) VALUES ('".$name."','".$description."','".$outputfile."')";
        $query = mysqli_query($db,$insert);
        if($query)
        {
            echo json_decode("Success");
            echo json_decode($return);
        }
}
else{
    $return["error"] = true;
    $return["msg"] = "No Image is submitted";
}
header('Content-Type: application/json');
?>

birdlist.php

<?php 
$db = mysqli_connect('localhost','root','','userdata');
if(!$db)
{
    echo "Database connection failed";
}
$data = mysqli_query($db,"SELECT * FROM birds");
$rows = array();
while ($r = mysqli_fetch_assoc($data))
{
    $rows[] = $r;
}
print json_encode($rows);
?>

pubspec.yaml

http: ^0.13.4 #to interact with api
image_picker: ^0.8.5

main.dart

import 'dart:convert';
import 'package:http/http.dart' as http;
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';

import 'AddBirdData.dart';
void main()=>runApp(MaterialApp(
  title: "Bird Data",
  debugShowCheckedModeBanner: false,
  theme: ThemeData(
    primarySwatch: Colors.indigo
  ),
  home: const Bird(),
));
class Bird extends StatefulWidget{
  const Bird({Key? key}) : super(key: key);
  @override
  _BirdState createState()=> _BirdState();
}
class _BirdState extends State<Bird>{
  late List birddata;
  Future<String> getBirdData() async{
    var response = await http.post(Uri.http("192.168.0.104",'/example/birdlist.php',{'q':'{http}'}));
    setState(() {
      birddata = json.decode(response.body);
    });
    return "Success!";
  }
  @override
  void initState(){
    getBirdData();
  }
  @override
  void dispose(){
    super.dispose();
  }
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: const Text('Birds'),
        actions: <Widget>[
          IconButton(onPressed:()=>Navigator.of(context).push(MaterialPageRoute(builder: (BuildContext context)=> const DataUpload())),
              icon: const Icon(
                Icons.add_circle_outline_sharp,
                color: Colors.white,
              ))
        ],),
      body: FutureBuilder<String>(
        future: getBirdData(),
        builder: (context,AsyncSnapshot<String> snapshot){
          if(snapshot.hasData)
            {
              return ListView.builder(
              itemBuilder: (BuildContext context, int index)
            {
              return Card(
              shape: const BeveledRectangleBorder(borderRadius: BorderRadius.all(Radius.circular(20))),
            semanticContainer: true,
            color: Colors.indigo,
            clipBehavior: Clip.antiAliasWithSaveLayer,
            child: Column(
            children: [
              Image.network('http://192.168.0.104/example/${birddata[index]["image"]}',fit: BoxFit.fill,),
              Padding(
                padding: const EdgeInsets.all(15.0),
                child: Text(birddata[index]["name"]+": "+birddata[index]["description"],
                  style: const TextStyle(fontWeight: FontWeight.bold,color: Colors.white,fontSize: 24),),
              ),
            ],
            ),
                margin: const EdgeInsets.only(top:10,bottom: 10,left: 10,right: 10),
            );
            },
            itemCount: birddata == null ? 0 : birddata.length,);
            }
          else{
            return Center(
              child: Container(),
            );
          }
      }
      ),
    );
  }
}

AddBirdData.dart

import 'dart:convert';
import 'package:http/http.dart' as http;
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';

import 'AddBirdData.dart';
void main()=>runApp(MaterialApp(
  title: "Bird Data",
  debugShowCheckedModeBanner: false,
  theme: ThemeData(
    primarySwatch: Colors.indigo
  ),
  home: const Bird(),
));
class Bird extends StatefulWidget{
  const Bird({Key? key}) : super(key: key);
  @override
  _BirdState createState()=> _BirdState();
}
class _BirdState extends State<Bird>{
  late List birddata;
  Future<String> getBirdData() async{
    var response = await http.post(Uri.http("192.168.0.104",'/example/birdlist.php',{'q':'{http}'}));
    setState(() {
      birddata = json.decode(response.body);
    });
    return "Success!";
  }
  @override
  void initState(){
    getBirdData();
  }
  @override
  void dispose(){
    super.dispose();
  }
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: const Text('Birds'),
        actions: <Widget>[
          IconButton(onPressed:()=>Navigator.of(context).push(MaterialPageRoute(builder: (BuildContext context)=> const DataUpload())),
              icon: const Icon(
                Icons.add_circle_outline_sharp,
                color: Colors.white,
              ))
        ],),
      body: FutureBuilder<String>(
        future: getBirdData(),
        builder: (context,AsyncSnapshot<String> snapshot){
          if(snapshot.hasData)
            {
              return ListView.builder(
              itemBuilder: (BuildContext context, int index)
            {
              return Card(
              shape: const BeveledRectangleBorder(borderRadius: BorderRadius.all(Radius.circular(20))),
            semanticContainer: true,
            color: Colors.indigo,
            clipBehavior: Clip.antiAliasWithSaveLayer,
            child: Column(
            children: [
              Image.network('http://192.168.0.104/example/${birddata[index]["image"]}',fit: BoxFit.fill,),
              Padding(
                padding: const EdgeInsets.all(15.0),
                child: Text(birddata[index]["name"]+": "+birddata[index]["description"],
                  style: const TextStyle(fontWeight: FontWeight.bold,color: Colors.white,fontSize: 24),),
              ),
            ],
            ),
                margin: const EdgeInsets.only(top:10,bottom: 10,left: 10,right: 10),
            );
            },
            itemCount: birddata == null ? 0 : birddata.length,);
            }
          else{
            return Center(
              child: Container(),
            );
          }
      }
      ),
    );
  }
}

Leave a Reply

Your email address will not be published.