如何在Dart/Flutter中将图像发送到api? [英] How to send an image to an api in dart/flutter?
本文介绍了如何在Dart/Flutter中将图像发送到api?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我看到了其他问题,但是那不是我想要的,我不想将图像上传到服务器,我不想转换为base64 ...
I saw other questions, but thats not what i want, i dont want to upload an image to a server, i dont want to convert to base64...
我只想以表单数据或其他形式发布文件,并获取返回的信息.
I only want to post a file in a form data or something else and get the returned info.
我有这个,但是没有用:
i have this, but has not work:
void onTakePictureButtonPressed() {
takePicture().then((String filePath) {
if (mounted) {
setState(() {
imagePath = filePath;
videoController?.dispose();
videoController = null;
});
http.post('http://ip:8082/composer/predict', headers: {
"Content-type": "multipart/form-data",
}, body: {
"image": filePath,
}).then((response) {
print("Response status: ${response.statusCode}");
print("Response body: ${response.body}");
});
if (filePath != null) showInSnackBar('Picture saved to $filePath');
}
});
}
推荐答案
最简单的方法是像 this中那样发布多部分请求.发布,然后将其发布到服务器.
The simplest method would be to post a multipart request like in this post and then post it to the server.
确保将它们导入文件的开头:
Make sure to import these in the beginning of the file:
import 'package:path/path.dart';
import 'package:async/async.dart';
import 'dart:io';
import 'package:http/http.dart' as http;
import 'dart:convert';
将此类添加到您的代码中的某个位置:
Add this class somewhere in your code:
upload(File imageFile) async {
// open a bytestream
var stream = new http.ByteStream(DelegatingStream.typed(imageFile.openRead()));
// get file length
var length = await imageFile.length();
// string to uri
var uri = Uri.parse("http://ip:8082/composer/predict");
// create multipart request
var request = new http.MultipartRequest("POST", uri);
// multipart that takes file
var multipartFile = new http.MultipartFile('file', stream, length,
filename: basename(imageFile.path));
// add file to multipart
request.files.add(multipartFile);
// send
var response = await request.send();
print(response.statusCode);
// listen for response
response.stream.transform(utf8.decoder).listen((value) {
print(value);
});
}
然后使用以下方式上传:
Then upload using:
upload(File(filePath));
在您的代码中:
void onTakePictureButtonPressed() {
takePicture().then((String filePath) {
if (mounted) {
setState(() {
imagePath = filePath;
videoController?.dispose();
videoController = null;
});
// initiate file upload
Upload(File(filePath));
if (filePath != null) showInSnackBar('Picture saved to $filePath');
}
});
}
这篇关于如何在Dart/Flutter中将图像发送到api?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文