c# - 如何解决 FileSystemException : Cannot retrieve length of file, path ='...' (OS Error : No such file or directory, errno = 2)

标签 c# asp.net flutter dart multipart

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

这是我的代码:

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 文件夹(通常是 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 命令行项目会更容易,您可以在其中访问项目文件夹中的 File

关于c# - 如何解决 FileSystemException : Cannot retrieve length of file, path ='...' (OS Error : No such file or directory, errno = 2),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59947233/

相关文章:

c# - C# 中 antlr 语法/解析器的无效转换问题

c# - NReco PDF 在 Azure 上有黑色方 block

listview - 控制Listview中元素的宽度 - flutter

flutter - 点击屏幕时调试控制台中的 "opservice is null false"消息

c# - 如何多次运行小 cucumber 场景

c# - 允许选定子对象的 Unity 自定义检查器

c# - 从多列检索数据并在单列中显示

c# - 为文本框控件链接必填字段和正则表达式验证器时出现问题

asp.net - Asp.Net MVC 3 应用程序中复杂子对象的集合?

c# - 如何使 flutter 应用程序的 http 获取请求到本地主机?