Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to send image through post using JSON in flutter?

Tags:

flutter

dart

I am building a flutter app, which utilizes image picker to capture or select an image from the gallery, but I am having a hard time how to POST that image to my server from the client side.

From what I gathered, I can send the local image via JSON by converting an image file to bytes and then sending it as BASE64.

import 'dart:convert';
import 'package:crypto/crypto.dart';

Future<Map> _avatarSubmit() async {
    String url = api + '/api/account';
    http.Response response = await http.post(Uri.encodeFull(url), headers: {
      "Accept": "application/json",
      "Cookie": "MYCOOKIE=" + sessionCookie2 + "; MYTOKENS=" + sessionCookie3,
      "Content-type": "multipart/form-data",
    }, body: {
      "image": "",
    });
    Map content = JSON.decode(response.body);
    return content;
  }

My question is how to convert an image file in the device into bytes, so I can then use crypto plugin to convert it to BASE64?

Thank you in advance.

like image 640
Ems Avatar asked Oct 31 '17 03:10

Ems


1 Answers

As image picker plugin provides the filePath of the image, you can use File class from dart:io to load the image and BASE64 from dart:convert to convert it as BASE64 string.

Here is how you can do it:

import 'dart:io';
import 'dart:convert';

File imageFile = new File(imageFilePath);
List<int> imageBytes = imageFile.readAsBytesSync();
String base64Image = BASE64.encode(imageBytes);

Hope this helped!

like image 178
Hemanth Raj Avatar answered Nov 03 '22 00:11

Hemanth Raj