【问题标题】:How to send an image to an api in dart/flutter?如何将图像发送到 dart/flutter 中的 api?
【发布时间】:2018-12-12 04:45:04
【问题描述】:

我看到了其他问题,但这不是我想要的,我不想将图像上传到服务器,我不想转换为 base64...

我只想以表单数据或其他方式发布文件并获取返回的信息。

我有这个,但没有工作:

  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');
      }
    });
  }

【问题讨论】:

    标签: post dart flutter form-data


    【解决方案1】:

    最简单的方法是在this post 中发布一个多部分请求,然后将其发布到服务器。

    确保在文件开头导入这些:

    import 'package:path/path.dart';
    import 'package:async/async.dart';
    import 'dart:io';
    import 'package:http/http.dart' as http;
    import 'dart:convert';
    

    在代码中的某处添加此类:

    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);
          });
        }
    

    然后使用上传:

    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');
          }
        });
      }
    

    【讨论】:

    • 我在发布的代码中写了几个 cmets。基本上,它打开一个将文件读取到字节流中,将其添加到多部分请求中,然后将其作为发布请求发送。你所要做的就是在你的代码中包含这个类并调用它。
    • @MetaCode 你需要导入包import 'package:async/async.dart'; 而不是import 'dart:async';。还有这个:import 'dart:convert';.
    • 好吧,你可以/应该用小写字符命名它:upload(...) 而不是Upload(...)。查看编辑后的帖子。
    • 我想在我的多部分请求中添加一个字段,例如 request .fields['name'] = DateTime.now().toIso8601String();但是,它每次都给我错误。但是,如果我给它一个像 request .fields['name'] = "test.png" 这样的静态值,它就可以工作。谁能告诉我我做错了什么?
    • 是否可以添加标题?
    【解决方案2】:
     import 'package:dio/dio.dart'; //From 3.x.x version
    
        uploadImage(){
            var formData = FormData();
            formData.files.add(MapEntry("Picture", await MultipartFile.fromFile(data.foto.path, filename: "pic-name.png"), ));
            var response = await dio.client.post('v1/post', data: formdata);
        }
    

    【讨论】:

    • 一点注意事项:将文件数组发送到 Spring Boot 应用程序时(不需要像“图片 []”这样的符号),我发现遵循此处的说明很有用: github.com/flutterchina/dio#multiple-files-upload - 如果你不想要“[]”,请阅读
    【解决方案3】:

    如果您将图像发送到 PHP Laravel 服务器。尝试在将size of the image 发送到服务器时减少它。我使用Image Picker 包来减小图像的大小。

    var image = await ImagePicker.pickImage(source: imageSource, imageQuality: 50, maxHeight: 500.0, maxWidth: 500.0);
    

    然后使用该图像创建一个多部分文件,将其添加到表单数据中,并使用带有dio 库的发布请求将表单数据发送到服务器。发送数据见@Elialber Lopes答案。

    它对我有用。

    【讨论】:

      猜你喜欢
      • 2021-03-14
      • 2021-04-04
      • 1970-01-01
      • 2023-01-05
      • 2023-03-18
      • 1970-01-01
      • 2020-10-28
      • 2019-09-15
      • 1970-01-01
      相关资源
      最近更新 更多