Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
2.1k views
in Technique[技术] by (71.8m points)

dart - How to send image through post using JSON in 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.

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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!


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...