如何将多个图像上传到 Flutter 中的 REST API?

Posted

技术标签:

【中文标题】如何将多个图像上传到 Flutter 中的 REST API?【英文标题】:How to upload Multiple Images to rest API in Flutter? 【发布时间】:2021-12-28 05:11:39 【问题描述】:

我正在尝试将多张图片上传到 Flutter 中的 Rest API。我写的代码如下:

  final List<File> _image = [];
  Future<Future<bool?>?> uploadImage(filePath, url) async 

  if (_image.length > 0) 
  for (var i = 0; i < _image.length; i++) 
    print(_image.length);
    var request =
        http.MultipartRequest('POST', Uri.parse(url + _scanQrCode));
    print(Uri.parse(url + _scanQrCode));
    request.files.add(http.MultipartFile.fromBytes(
      'picture',
      File(_image[i].path).readAsBytesSync(),
      filename: _image[i].path.split("/").last
    ));
    var res = await request.send();
      var responseData = await res.stream.toBytes();
      var result = String.fromCharCodes(responseData);
      print(_image[i].path);
  

  _submitedSuccessfully(context);
else
  return Fluttertoast.showToast(
      msg: "Please Select atleast one image",
      toastLength: Toast.LENGTH_SHORT,
      gravity: ToastGravity.CENTER,
      timeInSecForiosWeb: 1,
      backgroundColor: Colors.red,
      textColor: Colors.white,
      fontSize: 16.0
  );


代码不工作,图片没有上传。请任何人帮我解决这个问题

【问题讨论】:

【参考方案1】:

首先你创建变量

  List<File>? imageFileList = [];
 List<dynamic>? _documents = [];

当您从图库中选择图像时调用此方法

  pickMultipleImage(ImageSource source) async 
try 
  final images = await picker.pickMultiImage(
      maxWidth: 600, maxHeight: 600, imageQuality: 50);
  if (images == null) return;
  for (XFile image in images) 
    var imagesTemporary = File(image.path);
    imageFileList!.add(imagesTemporary);
  
 catch (e) 
  



当您按下按钮将图像发送到服务器时调用

   for(int i=0; i< _imageFileList!.length; i++ )
        var path = _imageFileList![i].path;
        _documents!.add(await MultipartFile.fromFile(path,
           filename: path.split('/').last));
                    
 var payload = dio.FromData.fromMap(   'documents': _documents);

Dio() response = Dio.post(url, data: payload);

【讨论】:

【参考方案2】:

这个包可以简化你的工作,flutter_uploader:

final uploader = FlutterUploader();

final taskId = await uploader.enqueue(
  url: "your upload link", //required: url to upload to
  files: [FileItem(filename: filename, savedDir: savedDir, fieldname:"file")], // required: list of files that you want to upload
  method: UploadMethod.POST, // HTTP method  (POST or PUT or PATCH)
  headers: "apikey": "api_123456", "userkey": "userkey_123456",
  data: "name": "john", // any data you want to send in upload request
  showNotification: false, // send local notification (android only) for upload status
  tag: "upload 1"); // unique tag for upload task
);

【讨论】:

【参考方案3】:

将您的代码更改为:

final List<File> _image = [];
Future<Future<bool?>?> uploadImage(String url) async 
     // create multipart request
     var request = http.MultipartRequest('POST', Uri.parse(url + _scanQrCode));
     
     
      if (_image.length > 0) 
        for (var i = 0; i < _image.length; i++) 
          request.files.add(http.MultipartFile('picture',
          File(_image[i].path).readAsBytes().asStream(), File(_image[i].path).lengthSync(),
          filename: basename(_image[i].path.split("/").last)));
        
        
        // send
        var response = await request.send();

      
        // listen for response
        response.stream.transform(utf8.decoder).listen((value) 
          debugPrint(value);
         _submitedSuccessfully(context);
       );
    
    else
  return Fluttertoast.showToast(
      msg: "Please Select atleast one image",
      toastLength: Toast.LENGTH_SHORT,
      gravity: ToastGravity.CENTER,
      timeInSecForIosWeb: 1,
      backgroundColor: Colors.red,
      textColor: Colors.white,
      fontSize: 16.0
     );
   

【讨论】:

基本名称出错 它不应该给出错误消息,除非它有一个来自空值列表的项目

以上是关于如何将多个图像上传到 Flutter 中的 REST API?的主要内容,如果未能解决你的问题,请参考以下文章

如何使用 HTTP 将多张图片上传到 Flutter 中的 Rest API?

Flutter - 将图像上传到 Firebase 存储

是否可以使用 Firebase 存储将多个图像添加到 Firebase 数据库? - 颤振

如何将内存中的图像上传为 Flutter web 中 body 上的二进制图像?

使用 Flutter 将图像上传到通用 Google Drive 帐户

在 Flutter Web 中上传多个文件(图像)