如何在Flutter中上传多个图像到rest API?

csga3l58  于 2022-12-19  发布在  Flutter
关注(0)|答案(6)|浏览(179)

我试图上传上传多个图像到休息API的Flutter。我写的代码如下所示:

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

代码不工作,图像不被上传。请任何人帮助我解决这个问题

gt0wga4j

gt0wga4j1#

首先创建to变量

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);
11dmarpk

11dmarpk2#

此方法可以简单地帮助上传多个图像

final uploadList = <MultipartFile>[];
for (final imageFiles in imageFileList!) {
    uploadList.add(
        await MultipartFile.fromFile(
            imageFiles.path,
            filename: imageFiles.path.split('/').last,
            contentType: MediaType('image', 'jpg'),
        ),
    );
}
g52tjvyc

g52tjvyc3#

将您的代码更改为:

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

klh5stk14#

此软件包使您的工作更加轻松,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
);
rryofs0p

rryofs0p5#

您可以在此使用request.files.addAll作为示例:

Future uploadmultipleimage(List images) async {

var uri = Uri.parse("");
  http.MultipartRequest request = new http.MultipartRequest('POST', uri);
  request.headers[''] = '';
  request.fields['user_id'] = '10';
  request.fields['post_details'] = 'dfsfdsfsd';
  //multipartFile = new http.MultipartFile("imagefile", stream, length, filename: basename(imageFile.path));
  List<MultipartFile> newList = new List<MultipartFile>();
  for (int i = 0; i < images.length; i++) {
    File imageFile = File(images[i].toString());
    var stream =
        new http.ByteStream(DelegatingStream.typed(imageFile.openRead()));
    var length = await imageFile.length();
    var multipartFile = new http.MultipartFile("imagefile", stream, length,
        filename: basename(imageFile.path));
    newList.add(multipartFile);
  }
  request.files.addAll(newList);
  var response = await request.send();
  if (response.statusCode == 200) {
    print("Image Uploaded");
  } else {
    print("Upload Failed");
  }
  response.stream.transform(utf8.decoder).listen((value) {
    print(value);
  });
}
sq1bmfud

sq1bmfud6#

我遇到了同样的问题,我使用了大多数答案中提到的技术,但它一直只发送我上传的一张图片,而不是发送所有图片。所以我所做的很简单。就像HTML字段一样,我使用了一个数组字段名。请看下面的代码:

final List<http.MultipartFile> photos = <http.MultipartFile>[];
  if (carFormModel.photos != null && carFormModel.photos!.length > 0) {
    await Future.forEach(carFormModel.photos!, (XFile file) async {
      var photo = await http.MultipartFile.fromPath("photos[]", file.path);
      photos.add(photo);
    });
  }

解释:我遍历了一个Getx文件列表(XFile)并且我使用了httpMultipartFile类的fromPath构造函数来填充我的临时空列表photos。我所做的与其他答案不同的是作为fromPath构造函数的第一个参数,我使用了一个数组变量photos[ ],而不是简单的变量photos。如果有问题的话,我的API是用Laravel制作的。希望这对你有帮助。

相关问题