How can I solve FileSystemException: Cannot retrieve length of file, path ='...' (OS Error: No such file or directory, errno = 2)

How can I solve FileSystemException: Cannot retrieve length of file, path ='...' (OS Error: No such file or directory, errno = 2)

我正在尝试将用户模型从 dart 发送到 api,其中我的文件在我的 c# 后端中设置为“IFormFile”数据类型。 我尝试使用多部分请求,但我得到的只是错误说明,我不明白为什么它无法检索文件的长度。

这是我的代码:

updateUser() async {
var uri = Uri.parse('http://myIP:8070/api/Users');
var request = http.MultipartRequest('Put', uri);
request.fields['id']="07bb2a17-7cd5-471b-973a-4b77d239b6c3";
request.fields['username']="beeso";
request.fields['email']="jake-username2@gmail.com";
request.fields['password']="Jake123-";
request.fields["oldPassword"]="Jake124-";
request.fields["gender"]="Male";
request.fields["dateOfBirth"]=DateTime.now().toString();
request.fields["name"]="dsjnss";
request.fields["languages"]=["Language1","Language2"].toString();
request.fields["nationalities"]=["Nationality1","Nationality2"].toString();
request.fields["phoneNumber"]="70502030";
request.fields["biography"]="jdnknkdas";
request.fields["info"]="asndasnkdas";
request.fields["religion"]="Christian";
request.fields["location"]="LA";
File imageFile = new File('Anatomy_of_a_Sunset-2.jpg');
var stream = new http.ByteStream(DelegatingStream.typed(imageFile.openRead()));
var length = await imageFile.length();
var multipartFile = new http.MultipartFile('file', stream, length,
    filename: basename(imageFile.path));
request.files.add(multipartFile);
Map<String, String> headers = {
  "content-type": "application/json"
};

request.headers.addAll(headers);
http.StreamedResponse response = await request.send();
print(response.statusCode);


}

如有任何帮助,我们将不胜感激。

This picture shows where my file is located

在 Flutter 中,您无法直接从项目中访问文件。您需要将它们添加到资产文件夹(通常为 assets)和 pubspec.yaml。然后,不使用 File 来阅读它们,而是使用 rootBundle(或 Asset 类 之一)。

var multipartFile = http.MultipartFile.fromBytes(
  'file',
  (await rootBundle.load('assets/anatomy.jpg')).buffer.asUint8List(),
  filename: 'anatomy.jpg', // use the real name if available, or omit
  contentType: MediaType('image', 'jpg'),
);

request.files.add(multipartFile);

在测试您的 API 时,您可能会发现创建一个 Dart 命令行项目更容易,您可以在其中访问项目文件夹中的 Files。

我的情况是图片上传问题,我通过使用解决了 xfile.path 图像选择器返回

XFile? image = await _picker.pickImage(
            source: ImageSource.gallery,
            imageQuality: 50,
            maxHeight: 500,
            maxWidth: 500);

#颤振 #dio