Flutter Upload Image to Server

Last updated Nov 25, 2021

In this flutter example we will learns about how to upload image to backend server. In many mobile applications there will be scenario to update profile pic. To upload profile image user will pick image from gallery and upload to server.

In this flutter application to upload image to backend server we will use dio library. To pick image from gallery we will use Image Picker library.

 

Let's get started

Step 1: Create Flutter application

Step 2: Add required dependencies in pubspec.yaml file.

Step 3: Let design our profile update UI

This UI will contains image to display and upload icon to pick image from gallery and Upload Button

 

Step 4: Pick Image from Gallery using ImagePicker

final ImagePicker _picker = ImagePicker();

void _pickImage() async {
   try {
  final pickedFile = await _picker.pickImage(source: ImageSource.gallery);
  _imageFile = pickedFile!.path;

   } catch (e) {
    print("Image picker error " + e.toString());
  }
}

 

This will ask the user to pick image from gallrey and return the image file path.

 

Step 5: Create Upload Image in FormData format

late FormData formData ;
uploadImage() async {
  print("Image picker uploading11 " );

   try{

  Map fileMap = {};
  File file = File(_imageFile);
  String fileName ="profile_pic";
  fileMap["profile_picture"] =
      MultipartFile(file.openRead(), await file.length(), filename: fileName);

  formData = FormData.fromMap({
    "image":fileMap
  });

   }catch (e) {
     print("Image picker error " + e.toString());
   }


}

 

Step 6: Create Dio instance and make api call to upload image to server.

 Dio dio=Dio();
 dio..interceptors.add(InterceptorsWrapper(
     onRequest:(options, handler){
       // Do something before request is sent
       print("Image Upload Resposne 1 ${options.data}" );
       return handler.next(options); //continue
       
     },
     onResponse:(response,handler) {

       print("Image Upload Resposne 2 ${response.statusCode}" );
       print("Image Upload Resposne 2 ${response.data}" );
       return handler.next(response); // continue
       
     },
     onError: (DioError e, handler) {
       // Do something with response error
       print("Image Upload Resposne 12 ${e.error}" );
       return  handler.next(e);//continue
       
     }
 ));
Response apiRespon =  await dio.post("",data: formData,options: Options(method: "POST", headers: {'Content-Type': 'multipart/form-data',
  },));
if(apiRespon.statusCode== 201){
   apiRespon.statusCode==201;
}else{
  print('errr');

}

 

In the above add your ImageUpload API end point and add requested parameters

 

Step 7: Now run application and you can able to upload image to server.

 

Complete example code to upload images to server.

import 'dart:io';

import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:image_picker/image_picker.dart';

import 'events/events_details.dart';
import 'home/homepage.dart';

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

class MyApp extends StatelessWidget {

  MyApp({Key? key}) : super(key: key);
  late String _imageFile;
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
        title: 'Upload Image to Server',
        theme: ThemeData(
          primarySwatch: Colors.blue,
        ),
        home: HomePage()/*Scaffold(
        body:Stack(
            children: [

              CircleAvatar(
                  radius: 72.0,
                  backgroundColor: Colors.transparent,
                  backgroundImage: NetworkImage("https://www.whatsappprofiledpimages.com/wp-content/uploads/2021/08/Profile-Photo-Wallpaper.jpg"),
              ),
              Positioned(
                  bottom: 0,
                  right: 0,
                  child: Container(
                    height: 40,
                    width: 40,
                    decoration: BoxDecoration(
                      shape: BoxShape.circle,
                      border: Border.all(
                        width: 4,
                        color: Theme.of(context).scaffoldBackgroundColor,
                      ),
                      color: Colors.red,
                    ),
                    child: TextButton(
                      onPressed: () {

                        _pickImage();
                      },
                      child: Icon(
                        Icons.edit,
                        color: Colors.white,
                      ),
                    ),
                  )),

            ]),
      ),*/
    );
  }

  final ImagePicker _picker = ImagePicker();

  void _pickImage() async {
    try {
      final pickedFile = await _picker.pickImage(source: ImageSource.gallery);
      _imageFile = pickedFile!.path;
      await uploadImage();


    } catch (e) {
      print("Image picker error " + e.toString());
    }
  }

  late FormData formData ;
  uploadImage() async {
    print("Image picker uploading11 " );
    File file = File(_imageFile);
    try{

      Mapg, MultipartFile> fileMap = {};

      String fileName ="profile_pic";
      fileMap["profile_picture"] =
          MultipartFile(file.openRead(), await file.length(), filename: fileName);

      formData = FormData.fromMap({
        "id": "34",
        "profile_picture": "",
        "sendimage":fileMap
      });

    }catch (e) {
      print("Image picker error " + e.toString());
    }






    Dio dio=Dio();
    dio..interceptors.add(InterceptorsWrapper(
        onRequest:(options, handler){
          // Do something before request is sent

          return handler.next(options); //continue

        },
        onResponse:(response,handler) {


          return handler.next(response); // continue

        },
        onError: (DioError e, handler) {

          return  handler.next(e);//continue

        }
    ));

    Response apiRespon =  await dio.post("Add your URL",data: formData,options: Options(method: "POST", headers: {'Content-Type': 'multipart/form-data;charset=UTF-8',
      'Charset': 'utf-8'},));
    print("Image Upload ${apiRespon}");

    if(apiRespon.statusCode== 201){
      apiRespon.statusCode==201;
    }else{
      print('errr');

    }

  }
}

 

In the same way we can also upload image to server as Base64 String format, you can read how to convert Base64 String to Image


Article Contributed By :
https://www.rrtutors.com/site_assets/profile/assets/img/avataaars.svg

2482 Views

Subscribe For Daily Updates

Flutter Questions
Android Questions