Home > Software design >  Upload Image to Server in flutter
Upload Image to Server in flutter

Time:09-21

I have started flutter recently and I wanted to upload Image on my php server.
I have used image_picker: ^0.8.5 3 and http: ^0.13.5 .
the image picker works fine but after clicking for uploading image on php server , I am getting try and catch error : "Error during converting to Base64" :(
here is the main.dart :

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

void main() {
  runApp(const MyApp());
}

class MyApp extends StatefulWidget {
  const MyApp({super.key});

  @override
  State<MyApp> createState() {
    return _MyAppState();
  }
}

class _MyAppState extends State<MyApp> {


  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      title: 'Image Upload',
      theme: ThemeData(
        primarySwatch: Colors.indigo,
      ),
      home: const ImageUpload(),
    );
  }
}


class ImageUpload extends StatefulWidget {
  const ImageUpload({Key? key}) : super(key: key);

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

class _ImageUpload extends State<ImageUpload> {
  final ImagePicker _picker = ImagePicker();
  File? uploadimage;

  Future<void> chooseImage() async {
    var choosedimage = await _picker.pickImage(source: ImageSource.gallery);
    setState(() {
      uploadimage = File(choosedimage!.path);
    });
  }

  Future<void> uploadImage() async {
    var uploadurl = Uri.parse('http://192.168.1.9/flutter/uploadimage.php');
    try {
      List<int> imageBytes = uploadimage!.readAsBytesSync();
      print(imageBytes);
      String baseimage = base64Encode(imageBytes);
      var response = await http.post(uploadurl, body: {
        'image': baseimage,
      });
      if (response.statusCode == 200) {
        var jsondata = json.decode(response.body);
        if (jsondata["error"]) {
          print(jsondata["msg"]);
        } else {
          print("Upload successful");
        }
      } else {
        print("Error during connection to server");
      }
    } catch (e) {
      print("Error during converting to Base64");
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Center(
          child: Text("Upload Image to Server"),
        ),
        backgroundColor: Colors.deepOrangeAccent,
      ),
      body: Container(
        height: 300,
        alignment: Alignment.center,
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            Container(
                child: uploadimage == null
                    ? Container()
                    : SizedBox(height: 150, child: Image.file(uploadimage!))),
            Container(
                child: uploadimage == null
                    ? Container()
                    : ElevatedButton.icon(
                        onPressed: () {
                          uploadImage();
                        },
                        icon: const Icon(Icons.file_upload),
                        label: const Text("UPLOAD IMAGE"),
                      )),
            ElevatedButton.icon(
              onPressed: () {
                chooseImage();
              },
              icon: const Icon(Icons.folder_open),
              label: const Text("CHOOSE IMAGE"),
            )
          ],
        ),
      ),
    );
  }
}


and my uploadimage.php file which runs on xampp :

<?php 
$return["error"] = false;
$return["msg"] = "";
if(isset($_POST["image"])){
    $base64_string = $_POST["image"];
    $outputfile = "uploads/image.jpg" ;
    $filehandler = fopen($outputfile, 'wb' ); 
    fwrite($filehandler, base64_decode($base64_string));
    fclose($filehandler); 
}else{
    $return["error"] = true;
    $return["msg"] =  "No image is submited.";
}

header('Content-Type: application/json');
echo json_encode($return);
?>

any Ideas or better approaches ?

CodePudding user response:

please try this way

final ByteStream stream =
          http.ByteStream(Stream.castFrom(imageFile.openRead()));
      final int length = await imageFile.length();



      final request = http.MultipartRequest('POST', uri);
      final multipartFile = http.MultipartFile(
          'file', stream, length,
          filename: basename(imageFile.path));


      request.files.add(multipartFile);
      final StreamedResponse response = await request.send();


CodePudding user response:

var response = await http.post(uploadurl,
     body: {
        'image': baseimage,
      });

to this

import 'dart:convert';

...
var response = await http.post(uploadurl, 
   body: jsonEncode({
        'image': baseimage,
      })
);

this is the tips to help you debuging

catch (e) {
  // print the error instead.
  //so you know what is the issue
   print("Error:  $e");
}
  • Related