San*_*nam 4 file-upload file-read .net-core webapi
我正在使用 dotnet core 开发 webApi,该核心从 IFormFile 获取 excel 文件并读取其内容。我正在关注文章 https://levelup.gitconnected.com/reading-an-excel-file-using-an-asp-net- core-mvc-application-2693545577db正在做同样的事情,只不过这里的文件存在于服务器上,而我的文件将由用户提供。
这是代码:
public IActionResult Test(IFormFile file)
{
List<UserModel> users = new List<UserModel>();
System.Text.Encoding.RegisterProvider(System.Text.CodePagesEncodingProvider.Instance);
using (var stream = System.IO.File.Open(file.FileName, FileMode.Open, FileAccess.Read))
{
using (var reader = ExcelReaderFactory.CreateReader(stream))
{
while (reader.Read()) //Each row of the file
{
users.Add(new UserModel
{
Name = reader.GetValue(0).ToString(),
Email = reader.GetValue(1).ToString(),
Phone = reader.GetValue(2).ToString()
});
}
}
}
return Ok(users);
}
}
Run Code Online (Sandbox Code Playgroud)
当 system.IO 尝试打开文件时,它无法找到路径,因为路径不存在。如何获取文件路径(根据用户选择的文件而有所不同)?还有其他方法可以实现吗?
PS:我不想先将文件上传到服务器上,然后再读取。
Ara*_*kis 10
您正在使用该file.FileName属性,它指的是浏览器发送的文件名。很高兴知道,但服务器上还不是真正的文件。您必须使用CopyTo(Stream)方法来访问数据:
public IActionResult Test(IFormFile file)
{
List<UserModel> users = new List<UserModel>();
System.Text.Encoding.RegisterProvider(System.Text.CodePagesEncodingProvider.Instance);
using (var stream = new MemoryStream())
{
file.CopyTo(stream);
stream.Position = 0;
using (var reader = ExcelReaderFactory.CreateReader(stream))
{
while (reader.Read()) //Each row of the file
{
users.Add(new UserModel{Name = reader.GetValue(0).ToString(), Email = reader.GetValue(1).ToString(), Phone = reader.GetValue(2).ToString()});
}
}
}
return Ok(users);
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
10678 次 |
| 最近记录: |