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.
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!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With