如何解决 FileSystemException: 无法检索文件长度,路径 ='...'

Alt*_*sif 8 flutter

    E/flutter ( 8324): [ERROR:flutter/lib/ui/ui_dart_state.cc(209)] Unhandled Exception: FileSystemException: Cannot retrieve length of file, path = 'File: '/data/user/0/com.example.upload/cache/file_picker/download (1).jpeg'' (OS Error: No such file or directory, errno = 2)
E/flutter ( 8324): #0      _File.length.<anonymous closure> (dart:io/file_impl.dart:366:9)
E/flutter ( 8324): #1      _rootRunUnary (dart:async/zone.dart:1434:47)
E/flutter ( 8324): #2      _CustomZone.runUnary (dart:async/zone.dart:1335:19)
E/flutter ( 8324): <asynchronous suspension>
E/flutter ( 8324): #3      uploadmultipleimage (package:upload/image_upload.dart:42:18)
E/flutter ( 8324): <asynchronous suspension>
E/flutter ( 8324): #4      WriteSQLdataState.build.<anonymous closure> (package:upload/upload_screen.dart:212:33)
E/flutter ( 8324): <asynchronous suspension>
E/flutter ( 8324): 



    Future uploadImg(List<File> img)async{
  final request = http.MultipartRequest("POST", Uri.parse("http://192.168.94.221/easy/uploadfile.php"));
  for (final file in img) {
    File imageFile = File(img.toString());
    var stream =
    http.ByteStream(DelegatingStream.typed(imageFile.openRead()));
    var length = await imageFile.length();
    print(length);
    var multipartFile = http.MultipartFile("file",stream, length, filename: basename(file.path));
    request.files.add(multipartFile);
    print(file.path);
    var myRequest = await request.send();
    var response = await http.Response.fromStream(myRequest);
    if(myRequest.statusCode == 200){
      //return jsonDecode(response.body);
      print('upload sucess');
    }else{
      print("Error ${myRequest.statusCode}");
    }

  }
  //request.headers[HttpHeaders.authorizationHeader] = '';
  // request.headers[HttpHeaders.acceptHeader] = 'application/json';

  final response = await request.send();
  if(response.statusCode == 200)
  {
    print("image sent${response.statusCode}");
  }else{
    print("ERROR");
  }
}
Run Code Online (Sandbox Code Playgroud)

我正在尝试使用http将多个图像上传到服务器,我可以一次上传一张图片,但我需要同时上传多个图像文件,这是我的功能:

Vic*_*ele 6

问题:

问题是您正在下面的行中创建一个新文件,但您将文件的字符串表示形式而不是文件的路径传递到新文件对象中。

    File imageFile = File(img.toString());
Run Code Online (Sandbox Code Playgroud)

这就是为什么错误消息中的路径是'File: '/data/user/0/com.example.upload/cache/file_picker/download (1).jpeg'找不到的。

解决方案:

有两种方法可以解决这个问题:

  1. File使用文件路径而不是字符串表示来创建新对象。

    更改这一行:

        File imageFile = File(img.toString());
    
    Run Code Online (Sandbox Code Playgroud)

    对此:

    File imageFile = File(file.path);
    
    Run Code Online (Sandbox Code Playgroud)
  2. file直接在循环中使用该对象,无需创建新File对象。将您的 for 循环更新为:

    File imageFile = File(img.toString());
    
    Run Code Online (Sandbox Code Playgroud)