How to use Image Picker and upload file to PHP server

See the example below and learn how to use Image Picker from Gallery or Camera and upload files to the server using PHP. In this example, first, we choose the file and convert to base64 encoding and upload as a string and in the server, we convert base64 encoding string to a binary file. Here, I have used the REST API to communicate with the server.

First, add http package and image_picker Flutter package as a dependency by adding the following line in your pubspec.yaml file.

See this also: How to pick file (images, docs, pdf, videos) and upload to PHP server with progress percentage

dependencies:
  flutter:
    sdk: flutter
  http: ^0.12.1
  image_picker: ^0.6.6+1

Add Internet Permission by adding this line in android/app/src/main/AndroidManifest.xml before <application>

<uses-permission android:name="android.permission.INTERNET"/>

Image Picker and Dart Code:

import 'dart:convert';
import 'dart:io';
import 'package:flutter/material.dart';
import 'package:flutter/widgets.dart';
import 'package:image_picker/image_picker.dart';
import 'package:http/http.dart' as http;
//import http package manually

class ImageUpload extends StatefulWidget{
  @override
  State<StatefulWidget> createState() {
    return _ImageUpload();
  }
}

class _ImageUpload extends State<ImageUpload>{

  File uploadimage; //variable for choosed file

  Future<void> chooseImage() async {
        var choosedimage = await ImagePicker.pickImage(source: ImageSource.gallery);
        //set source: ImageSource.camera to get image from camera
        setState(() {
            uploadimage = choosedimage;
        });
  }

  Future<void> uploadImage() async {
     //show your own loading or progressing code here

     String uploadurl = "http://192.168.0.112/test/image_upload.php";
     //dont use http://localhost , because emulator don't get that address
     //insted use your local IP address or use live URL
     //hit "ipconfig" in windows or "ip a" in linux to get you local IP

    try{
      List<int> imageBytes = uploadimage.readAsBytesSync();
      String baseimage = base64Encode(imageBytes);
      //convert file image to Base64 encoding
      var response = await http.post(
              uploadurl, 
              body: {
                 'image': baseimage,
              }
      );
      if(response.statusCode == 200){
         var jsondata = json.decode(response.body); //decode json data
         if(jsondata["error"]){ //check error sent from server
             print(jsondata["msg"]);
             //if error return from server, show message from server
         }else{
             print("Upload successful");
         }
      }else{
        print("Error during connection to server");
        //there is error during connecting to server,
        //status code might be 404 = url not found
      }
    }catch(e){
       print("Error during converting to Base64");
       //there is error during converting file image to base64 encoding. 
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
         appBar: AppBar(
           title: Text("Upload Image to Server"),
           backgroundColor: Colors.deepOrangeAccent,
         ),
         body:Container(
             height:300,
             alignment: Alignment.center,
             child:Column(
                    mainAxisAlignment: MainAxisAlignment.center, //content alignment to center 
                    children: <Widget>[
                        Container(  //show image here after choosing image
                            child:uploadimage == null? 
                               Container(): //if uploadimage is null then show empty container
                               Container(   //elese show image here
                                  child: SizedBox( 
                                     height:150,
                                     child:Image.file(uploadimage) //load image from file
                                  )
                               )
                        ),

                        Container( 
                            //show upload button after choosing image
                          child:uploadimage == null? 
                               Container(): //if uploadimage is null then show empty container
                               Container(   //elese show uplaod button
                                  child:RaisedButton.icon(
                                    onPressed: (){
                                        uploadImage();
                                        //start uploading image
                                    }, 
                                    icon: Icon(Icons.file_upload), 
                                    label: Text("UPLOAD IMAGE"),
                                    color: Colors.deepOrangeAccent,
                                    colorBrightness: Brightness.dark,
                                    //set brghtness to dark, because deepOrangeAccent is darker coler
                                    //so that its text color is light
                                  )
                               ) 
                        ),

                        Container(
                          child: RaisedButton.icon(
                            onPressed: (){
                                chooseImage(); // call choose image function
                            },
                            icon:Icon(Icons.folder_open),
                            label: Text("CHOOSE IMAGE"),
                            color: Colors.deepOrangeAccent,
                            colorBrightness: Brightness.dark,
                          ),
                        )
              ],),
          ),
    );
  }
}

PHP code: test/image_upload.php

<?php 
$return["error"] = false;
$return["msg"] = "";
//array to return

if(isset($_POST["image"])){
    $base64_string = $_POST["image"];
    $outputfile = "uploads/image.jpg" ;
    //save as image.jpg in uploads/ folder

    $filehandler = fopen($outputfile, 'wb' ); 
    //file open with "w" mode treat as text file
    //file open with "wb" mode treat as binary file
    
    fwrite($filehandler, base64_decode($base64_string));
    // we could add validation here with ensuring count($data)>1

    // clean up the file resource
    fclose($filehandler); 
}else{
    $return["error"] = true;
    $return["msg"] =  "No image is submited.";
}

header('Content-Type: application/json');
// tell browser that its a json data
echo json_encode($return);
//converting array to JSON string

In this way, you can upload images to the server using PHP from Flutter App.

No any Comments on this Article


Please Wait...