如何在Flutter中使用JSON通过帖子发送图片? [英] How to send image through post using JSON in flutter?
问题描述
我正在构建一个Flutter应用,该应用利用图像选择器来捕获或选择图像画廊,但是我很难将图像从客户端发布到服务器。
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.
从我收集的信息中,我可以通过通过将图像文件转换为字节然后将其作为BASE64发送来进行JSON。
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;
}
我的问题是如何将设备中的图像文件转换为字节,所以然后,我可以使用 crypto 插件将其转换为BASE64吗?
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?
谢谢。
推荐答案
以图像选择器插件提供了图像的filePath,您可以使用dart:io中的File类加载图像,并使用dart:convert中的BASE64将其转换为BASE64
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.
这是您的操作方式:
import 'dart:io';
import 'dart:convert';
File imageFile = new File(imageFilePath);
List<int> imageBytes = imageFile.readAsBytesSync();
String base64Image = BASE64.encode(imageBytes);
希望有帮助!
这篇关于如何在Flutter中使用JSON通过帖子发送图片?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!