Met*_*uru 22 parsing file-upload asp.net-core
说你有这个动作:
public List<string> Index(IFormFile file){
//extract list of strings from the file
return new List<string>();
}
Run Code Online (Sandbox Code Playgroud)
我已经找到了很多将文件保存到驱动器的示例,但是如果我想跳过这个并且只是直接从IFormFile读取文本行到内存中的数组怎么办?
Dav*_*ine 36
您应该能够执行以下操作:
public List<string> Index(IFormFile file) => file.ReadAsList();
Run Code Online (Sandbox Code Playgroud)
IFormFile有一个.OpenReadStream方法的抽象.
更新
为了防止大量不合需要的和可能很大的分配,我们应该一次读取一行并从每一行构建我们的列表.此外,我们可以将此逻辑封装在扩展方法中.该Index行动最终看起来是这样的:
public static List<string> ReadAsList(this IFormFile file)
{
var result = new StringBuilder();
using (var reader = new StreamReader(file.OpenReadStream()))
{
while (reader.Peek() >= 0)
result.AppendLine(reader.ReadLine());
}
return result;
}
Run Code Online (Sandbox Code Playgroud)
相应的扩展方法如下所示:
public static async Task<string> ReadAsStringAsync(this IFormFile file)
{
var result = new StringBuilder();
using (var reader = new StreamReader(file.OpenReadStream()))
{
while (reader.Peek() >= 0)
result.AppendLine(await reader.ReadLineAsync());
}
return result.ToString();
}
Run Code Online (Sandbox Code Playgroud)
同样你也可以有一个async版本:
public Task<List<string>> Index(IFormFile file) => file.ReadAsListAsync();
Run Code Online (Sandbox Code Playgroud)
然后你可以这样使用这个版本:
public List<string> Index(IFormFile file) => file.ReadAsList();
Run Code Online (Sandbox Code Playgroud)
更新2
IFormFile 版:
public static List<string> ReadAsList(this IFormFile file)
{
var result = new StringBuilder();
using (var reader = new StreamReader(file.OpenReadStream()))
{
while (reader.Peek() >= 0)
result.AppendLine(reader.ReadLine());
}
return result;
}
Run Code Online (Sandbox Code Playgroud)
Alp*_*glu 13
ASP.NET Core 3.0 - 将表单文件的内容读入字符串
public static async Task<string> ReadFormFileAsync(IFormFile file)
{
if (file == null || file.Length == 0)
{
return await Task.FromResult((string)null);
}
using (var reader = new StreamReader(file.OpenReadStream()))
{
return await reader.ReadToEndAsync();
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
17080 次 |
| 最近记录: |