Ahmed
Ahmed

Reputation: 49

flutter post request to server with file

Dears, I am new at flutter, I want to send post request from flutter to server and this is the postman request

Image-Post-Request

Post header:

key Value

Accept: application/json

Content-Type: application/x-www-form-urlencoded

Post Authentication:

Bear Token

Post Body:

key : Value

address : address

description: description

feedback: feedback

media: download.png

I want to make this request from flutter This is my code:

File _img; // taken by camera

Map<String,String> headers = {
        'Content-Type':'application/json',
        'Authorization': 'Bearer $token',
      };

 final msg = jsonEncode({
        "address"    : _address,
        "description": _description,
        "feedback"   : _techicalSupport,
        "media"      : _img;
       });


 try{
        var response = await http.post(
          "url",
          headers: headers,
          body: msg,
        );
        print("${response.toString()}");
   }catch(e){
        print("${e.toString()}");
    }

I got this Error: Unhandled Exception: Converting object to an encodable object failed: Instance of '_File'

Note: media is not required, when I removed it from the body it works and it create record in the database

I want to include media in the body. How can I do it please...

Upvotes: 1

Views: 2898

Answers (4)

Ahmed
Ahmed

Reputation: 49

This is the answer of my question, I used Dio library :

  import 'package:dio/dio.dart';

    File myImage;
    List<File> _images = [];


    // to handle image and make list of images
    _handleImage()async{
        File imageFile = await ImagePicker.pickImage(source: ImageSource.camera);
        if(imageFile != null){
            myImage = imageFile;
            _images.add(imageFile);
        }
      }



    // for post data with images
    void _submit() async{ 
        FormData formData = FormData();

        _images.forEach((image) async{
              formData.files.addAll(
                  [
                    MapEntry(
                      "media[]",
                      await dio.MultipartFile.fromFile(image.path),
                    ),
                  ]
              );
        });

        formData.fields.add(MapEntry("address", _address),);
        formData.fields.add(MapEntry("description", _description),);
        formData.fields.add(MapEntry("feedback", _techicalSupport),);

        var response = await new Dio().post(
            postUrl,
            options: Options(
              headers: {
                "Content-Type": "application/json",
                "Authorization" : 'Bearer $token',
              }
            ),
            data: formData
         );

        print("${response.toString()}");
    }

Upvotes: 3

MSaudi
MSaudi

Reputation: 4652

1.Configure FilePicker library (optional step, you may select your file using any library)

Then to pick the file

File file = await FilePicker.getFile();

2.Configure dio library , versions here

import 'package:dio/dio.dart';

then

FormData formData = FormData.fromMap({
 "FIELD_NAME_WEBSERVICE_HERE": await MultipartFile.fromFile(imageFile.path,filename: "anyname_or_filename"),
"FIELD_NAME_WEBSERVICE_HERE":"sample value for another field"),
              });

    var response = await Dio().post("FULL_URL_HERE", data: formData);

    print(response);

Upvotes: 1

easeccy
easeccy

Reputation: 5086

You should use MultipartRequest to send file.

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

void send() async {
  final msg = {
    "address": "test",
    "description": "test",
    "feedback": "test",
  };

  File _img;

  var image = await ImagePicker.pickImage(source: ImageSource.camera);

  _img = image;

  var response = await http.MultipartRequest(
      'POST', Uri.parse("url"))
    ..fields.addAll(msg)
    ..files.add(http.MultipartFile.fromBytes('image', _img.readAsBytesSync(),
        contentType: MediaType('image', 'jpeg'), filename: 'test.jpg'));


  print(response);
}

Upvotes: 0

Ravinder Kumar
Ravinder Kumar

Reputation: 7990

You need to convert _img to MultipartFile

    MultipartFile file=MultipartFile.fromBytes(
        'media', await filePath.readAsBytes(),
        filename: 'FILE_NAME');

    var request = http.MultipartRequest("POST", Uri.parse(url));
    if (files != null) request.files.add(file);

Upvotes: 0

Related Questions