【问题标题】:How to upload Multiple Images to rest API in Flutter?如何将多个图像上传到 Flutter 中的 REST API?
【发布时间】: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
  );
}
}

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

【问题讨论】:

    标签: flutter api rest http dart


    【解决方案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
             );
           }
        }
        

        【讨论】:

        • 基本名称出错
        • 它不应该给出错误消息,除非它有一个来自空值列表的项目
        猜你喜欢
        • 2021-02-05
        • 2020-07-08
        • 1970-01-01
        • 2021-06-06
        • 1970-01-01
        • 2021-12-16
        • 1970-01-01
        • 1970-01-01
        • 2012-07-24
        相关资源
        最近更新 更多