By karan vs

2017-06-30 08:11:39 8 Comments

I would like to upload a image, I am using http.Client() for making requests,

static uploadImage(String id, File file) {
  var httpClient = createHttpClient();

  Map<String, String> headers = new Map<String, String>();
  headers.putIfAbsent("Authorization", () => "---");
  headers.putIfAbsent("Content-Type", () => "application/json");

  var body=new List();
  body.add(id.),headers: headers,body: ,encoding: )

What should be the body and encoding part for the request ?


@Liam 2020-05-02 11:52:46

to get Body from request Instead of {

I use:

String body=await

@Boban 2020-04-22 17:36:57

Please try below solution

Future<String> uploadImageHTTP(file, url) async {

  var request = http.MultipartRequest('POST', Uri.parse(url));
  request.files.add(await http.MultipartFile.fromPath('picture', file.path));
  var res = await request.send();
  return res.reasonPhrase;


@samad shukr 2020-03-26 19:22:56

you can use the firstore_firebase to store the image

import 'dart:async';
import 'dart:io';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:image_picker/image_picker.dart';
import 'package:firebase_storage/firebase_storage.dart';

void main() => runApp(new MyApp());

class MyApp extends StatelessWidget {
  // This widget is the root of your application.
  Widget build(BuildContext context) {
    return new MaterialApp(
      title: 'Flutter Demo',
      theme: new ThemeData(
      home: new MyHomePage(),

class MyHomePage extends StatefulWidget {
  _MyHomePageState createState() => new _MyHomePageState();

class _MyHomePageState extends State<MyHomePage> {
  File sampleImage;

  Future getImage() async {
    var tempImage = await ImagePicker.pickImage(source:;

    setState(() {
      sampleImage = tempImage;

  Widget build(BuildContext context) {
    return new Scaffold(
      appBar: new AppBar(
        title: new Text('Image Upload'),
        centerTitle: true,
      body: new Center(
        child: sampleImage == null ? Text('Select an image') : enableUpload(),
      floatingActionButton: new FloatingActionButton(
        onPressed: getImage,
        tooltip: 'Add Image',
        child: new Icon(Icons.add),
      ), // This trailing comma makes auto-formatting nicer for build methods.

  Widget enableUpload() {
    return Container(
      child: Column(
        children: <Widget>[
          Image.file(sampleImage, height: 300.0, width: 300.0),
            elevation: 7.0,
            child: Text('Upload'),
            textColor: Colors.white,
            onPressed: () {
              final StorageReference firebaseStorageRef =
              final StorageUploadTask task =

@TejaDroid 2018-12-24 09:23:52

I have tried all the above but none worked for me to upload a file to a server.

After a deep search, I got a plugin the same as Dio.

The following code uploads a file to a server.

uploadFileFromDio(UserProfile userProfile, File photoFile) async {
    var dio = new Dio();
    dio.options.baseUrl = url;
    dio.options.connectTimeout = 5000; //5s
    dio.options.receiveTimeout = 5000;
    dio.options.headers = <Header Json>;
    FormData formData = new FormData();
    formData.add("user_id", userProfile.userId);

    if (photoFile != null &&
        photoFile.path != null &&
        photoFile.path.isNotEmpty) {
      // Create a FormData
      String fileName = basename(photoFile.path);
      print("File Name : $fileName");
      print("File Size : ${photoFile.lengthSync()}");
      formData.add("user_picture", new UploadFileInfo(photoFile, fileName));
    var response = await"user/manage_profile",
        data: formData,
        options: Options(
            method: 'POST',
            responseType: ResponseType.PLAIN // or ResponseType.JSON
    print("Response status: ${response.statusCode}");
    print("Response data: ${}");

@alex351 2019-04-10 12:27:44

Do you have any problems with content type? If I upload an image, I have to set the content type manually.

@TejaDroid 2019-04-10 12:59:40

"content-type" is basically set in header of api, so you have to add a header param as content-type whatever set by api developer there Some common examples of content types are “text/plain”, “application/xml”, “text/html”, “application/json”, “image/gif”, and “image/jpeg”.

@alex351 2019-04-10 13:17:08

I am sending files (images, documents etc) from mobile device to Node.js API, which uses multer for storing files to MongoDB. I also have a web application which communicates with the same API. If I upload the image over my mobile app and Dio plugin, the mime-type on the server and in my mobgodb is "application/octet-stream". If I upload it over my web app, the mime-type is "image/jpeg". I do not need to set content-type manually in my web app.

@Jigar Fumakiya 2019-06-20 06:18:06

I am uploading the image to the server but when I try to open an image that say's image is empty?

@Santiago 2019-10-24 05:07:54

How do I receive it in my .php?

@TejaDroid 2019-10-24 07:31:59

I'm not sure but may be you have to check the receiving request in your .php with "$_FILES", there you find all images from request with param user_profile

@evals 2019-11-24 14:35:54

the method add is not defined !!

@TejaDroid 2019-11-26 07:05:03

add method come from FormData class and its define in dio. So, please add latest dependancy of dio in your pubspec.yaml and then run Packages upgrade.

@Quick learner 2020-03-13 18:10:40

I found a working example without using any external plugin , this only uses

import 'package:http/http.dart' as http;


var stream =
        new http.ByteStream(DelegatingStream.typed(imageFile.openRead()));
    // get file length
    var length = await imageFile.length(); //imageFile is your image file
    Map<String, String> headers = {
      "Accept": "application/json",
      "Authorization": "Bearer " + token
    }; // ignore this headers if there is no authentication

    // string to uri
    var uri = Uri.parse(Constants.BASE_URL + "api endpoint here");

    // create multipart request
    var request = new http.MultipartRequest("POST", uri);

  // multipart that takes file
    var multipartFileSign = new http.MultipartFile('profile_pic', stream, length,
        filename: basename(imageFile.path));

    // add file to multipart

    //add headers

    //adding params
    request.fields['loginId'] = '12';
    request.fields['firstName'] = 'abc';
   // request.fields['lastName'] = 'efg';

    // send
    var response = await request.send();


    // listen for response {


@xiyulangzi 2019-02-07 09:25:16

my working code below, based on @TejaDroid's sample, it upload one image via the AWS Gateway API with a lambda function behind to store the image into S3.

uploadImageWithhttp(File imageFile, int serialno) async {
    var postBody= {
        'username': '[email protected]',  
        "productid": "1000123",             //TODO
        "imageno": serialno.toString(), 
        'image': imageFile != null ? base64Encode(imageFile.readAsBytesSync()) : '',

    final response = await
      headers: {
        //AuthUtils.AUTH_HEADER: _authToken
        'Content-Type' : 'application/json',
      body: json.encode(postBody),

    final responseJson = json.decode(response.body);


@Romil 2019-06-19 09:22:13

Import dio, image_picker library

    Future _onGalleryPressed() async {
            Future<File> image = ImagePicker.pickImage(source:;
            setState(() {
              this._imageFile = image;
            File img = await image;
            if (img != null) {
              //API CALL
              try {
                FormData formData = new FormData.from({"file": path});
                var url = backendUrl + "/upload-image";
                var token = await _getMobileToken();
                Map<String, String> headers = {
                  'Authorization': 'Bearer $token',
                  "Content-Type": "multipart/form-data",
                  "X-Requested-With": "XMLHttpRequest"
                  data: formData,
                  options: Options(
                      method: 'POST',
                      headers: headers,
                      responseType: ResponseType.json // or ResponseType.JSON
              } catch (e) {}

@Santiago 2019-10-24 05:08:20

How do I receive it in my .php?

@Shyju M 2018-04-04 07:22:55

Use MultipartRequest class

Upload(File imageFile) async {    
    var stream = new http.ByteStream(DelegatingStream.typed(imageFile.openRead()));
      var length = await imageFile.length();

      var uri = Uri.parse(uploadURL);

     var request = new http.MultipartRequest("POST", uri);
      var multipartFile = new http.MultipartFile('file', stream, length,
          filename: basename(imageFile.path));
          //contentType: new MediaType('image', 'png'));

      var response = await request.send();
      print(response.statusCode); {

name spaces:

import 'package:path/path.dart';
import 'package:async/async.dart';
import 'dart:io';
import 'package:http/http.dart' as http;

@alex351 2019-04-11 08:01:24

My uploaded file is always application/octet-stream. Is there a way to get the right content type from the file and how can I set it in the request?

@nivla360 2020-02-08 20:22:22

where do I import the MediaType class from

@nivla360 2020-02-08 20:26:07

I figured I just had to import 'package:http_parser/http_parser.dart';

@John Joe 2020-04-19 14:24:14

If I have multiple multipartFile, how should write?

@GunJack 2020-06-28 07:49:02

DelegatingStream.typed is deprecated.

@Raj Yadav 2019-06-13 02:32:42

The easiest way is to use the http library,

import 'dart:io';
import 'package:http/http.dart' as http;

_asyncFileUpload(String text, File file) async{
   //create multipart request for POST or PATCH method
   var request = http.MultipartRequest("POST", Uri.parse("<url>"));
   //add text fields
   request.fields["text_field"] = text;
   //create multipart using filepath, string or bytes
   var pic = await http.MultipartFile.fromPath("file_field", file.path);
   //add multipart to request
   var response = await request.send();

   //Get the response from the server
   var responseData = await;
   var responseString = String.fromCharCodes(responseData);

@Jon Stark 2019-07-26 09:01:07

Hello , its giving me Unhandled Exception: SocketException: OS Error: Broken pipe, errno = 32 , please suggest

@Raj Yadav 2019-07-27 13:36:48

Please check the URL. Make sure you're able to post your file data from Postman

@Santiago 2019-10-24 05:08:03

How do I receive it in my .php?

@Raj Yadav 2019-11-10 07:16:22

I am not much good at PHP but you can get files using $_FILES["file_field"]

@Sanjeev Sangral 2019-05-30 20:06:27

First of all choose your image from gallery or Camera

File _image;
Future _getImage() async {
var image = await ImagePicker.pickImage(source:;
setState(() {
_image = image;

Now call the below function on button click or inside the _getImage() function. With the file i'm uploading other fields also you see in the saveInAttendance()

Don't forget to import package :

import 'package:dio/dio.dart';
import 'package:path/path.dart';

Future saveInAttendance( BuildContext context,String entryType,String mode) async {
        Dio dio = new Dio();
        FormData formData = new FormData(); // just like JS
        formData.add("inimageFile", new UploadFileInfo(_image, basename(_image.path)));
        formData.add("EntryType", entryType);
        formData.add("emp_code", 5);
        formData.add("location",""+_startLocation.latitude.toString()+"-"+_startLocation.longitude.toString());, data: formData, options: Options(
            method: 'POST',
            responseType: ResponseType.json // or ResponseType.JSON
            .then((r) {
          setState(() {
            var data = json.decode(r.toString());
              warningAlert("Attendance Saved", "Your attendance saved Successfully",context);

For more Info you can visit Here

@Aravind Vemula 2018-07-13 09:33:53

Checkout the body in submitForm() method.

File _image;

Future cameraImage() async {
  var image = await ImagePicker.pickImage(
    maxHeight: 240.0,
    maxWidth: 240.0,

  setState(() {
    _image = image;

submitForm() async {
  final response = await
    headers: {
      AuthUtils.AUTH_HEADER: _authToken
    body: {
      'user_id': userId
      'photo': _image != null ? 'data:image/png;base64,' +
          base64Encode(_image.readAsBytesSync()) : '',

  final responseJson = json.decode(response.body);


@Santiago 2019-10-24 05:07:39

How do I receive it in my .php?

@Aravind Vemula 2019-10-24 09:46:02

@Santiago you need to decode and save. you can find solution here…

@Collin Jackson 2017-06-30 15:04:06

Consider using Flutter's Firebase Storage plugin -- it has features that could be useful for uploading large image files on a mobile connection.

I wrote the plugin, contributions and feedback are welcome!

@karan vs 2017-07-01 15:41:07

Thanks, I was able to do it with http client library

Related Questions

Sponsored Content

10 Answered Questions

[SOLVED] How to upload images and file to a server in Flutter?

3 Answered Questions

[SOLVED] Dart HTTP POST with Map<String, dynamic> as body

  • 2019-02-08 19:15:18
  • Touré Holder
  • 3370 View
  • 0 Score
  • 3 Answer
  • Tags:   json dart flutter

2 Answered Questions

[SOLVED] Very simple image loaded pretty slow with Flutter

  • 2019-06-03 20:17:24
  • Ronald Petit
  • 6172 View
  • 1 Score
  • 2 Answer
  • Tags:   flutter dart

1 Answered Questions

Flutter: Restrict calling build method many times

1 Answered Questions

[SOLVED] Flutter - How to download a file from server using binary stream

  • 2018-09-12 10:36:19
  • annalaufey
  • 2911 View
  • 3 Score
  • 1 Answer
  • Tags:   dart flutter

1 Answered Questions

[SOLVED] POST image to web service with Flutter

1 Answered Questions

[SOLVED] http post a map object using application/json content-type

  • 2014-03-19 17:41:09
  • user3438862
  • 1646 View
  • 2 Score
  • 1 Answer
  • Tags:   rest dart

Sponsored Content