flutter - 如何在 Flutter 中通过 Multipart 发送图像

我想将三张图片发送到我的服务器。我试过跟随。没有错误,没有异常,但我无法将图片发送到服务器。你能帮我看看我哪里出错了吗?

File? image1;

我正在从图库中挑选图片

Future pickImage1() async {
try {
  final image = await ImagePicker().pickImage(source: ImageSource.gallery,imageQuality: 75);
  if (image == null) return;
  final imagePermanent = await saveImagePermanently(image.path);
  setState(() => image1 = imagePermanent);
} on PlatformException catch (e) {
  print('failed to pick image $e');
}

}

这就是我尝试将图像发送到服务器的方式

uploadImage1(File imageFile1,File imageFile2, File imageFile3 ) async {
var postUri = Uri.parse("https://my link");
var request =  http.MultipartRequest('POST', postUri);
request.files.add( http.MultipartFile.fromBytes("image1", imageFile1.readAsBytesSync(), filename: "Photo1.jpg", ));
request.files.add( http.MultipartFile.fromBytes("image2", imageFile1.readAsBytesSync(), filename: "Photo2.jpg", ));
request.files.add( http.MultipartFile.fromBytes("image3", imageFile1.readAsBytesSync(), filename: "Photo3.jpg", )); 

 await request.send().then((response) {
  if (response.statusCode == 200)
  {
    print("Uploaded");
  }
  else {
    print('error');
  }
});

}

我在控制台中得到的是

error

这是我调用此功能的按钮

ElevatedButton(
              onPressed: () {
               uploadImage1(image1!, image2!, image3!);
                print('pressed');
              },
              child: const Text(' upload '),
            ),

回答1

不要同时使用 awaitthen。只需使用 await 等待异步函数执行完成即可。

final response = await request.send();
if (response.statusCode == 200) {
  print("Uploaded");
} else {
  print('error');
}

回答2

我有一个https://gist.github.com/warcayac/fdffe5e8282e39752af5fd963dd16789,可以将本地图片上传到https://my.plantnet.org,它可以对您有所帮助,该示例代码的输出是这样的:

Start fetching...
Fetching done!

{query: {project: all, images: [dc5f659df9a4bcf90fc109830564d821], organs: [leaf],
...
{id: 6411486}}], version: 2022-02-14 (5.1), remainingIdentificationRequests: 197}

Done!

相似文章

随机推荐

最新文章