如何读取将从 .Net Core API 中的表单上传的文件?

use*_*293 13 c# upload file asp.net-core-webapi

我在我的 .Net Core API 中创建了一个方法,它将上传一个文件。

[HttpPost]
public async Task<IActionResult> ReadFile(IFormFile file)
{
    return BadRequest(file);
}
Run Code Online (Sandbox Code Playgroud)

我这样做是return BadRequest(file)为了阅读邮递员发送给我的内容。

结果是这样的:

{
    "contentDisposition": "form-data; name=\"file\"; filename=\"data.dat\"",
    "contentType": "application/octet-stream",
    "headers": {
        "Content-Disposition": [
            "form-data; name=\"file\"; filename=\"data.dat\""
        ],
        "Content-Type": [
            "application/octet-stream"
        ]
    },
    "length": 200,
    "name": "file",
    "fileName": "data.dat"
Run Code Online (Sandbox Code Playgroud)

}

我在 Microsoft 文档中看到:

using (StreamReader sr = new StreamReader("TestFile.txt"))
{
    // Read the stream to a string, and write the string to the console.
        String line = sr.ReadToEnd();
        Console.WriteLine(line);
}
Run Code Online (Sandbox Code Playgroud)

但是用户必须选择一个文件来读取它,应用程序不必进入文件夹并读取文件。

有可能做到这一点吗?我可以有一些链接来帮助我做到这一点吗?

更新

我想方法 ReadFile 读取我的文件的内容,这些内容将被上传到表单。

所以我将有一个字符串,它将包含我的文件的内容,之后我将可以在这个文件中做所有我想做的事情。

例如,我有一个文件,在这个文件中它被写为LESSON,使用ReadFile方法我将获得字符串中的单词 course 。

Chr*_*att 15

该文件将绑定到您的IFormFile参数。您可以通过以下方式访问流:

using (var stream = file.OpenReadStream())
{
    // do something with stream
}
Run Code Online (Sandbox Code Playgroud)

如果要将其作为字符串读取,则需要一个实例StreamReader

string fileContents;
using (var stream = file.OpenReadStream())
using (var reader = new StreamReader(stream))
{
    fileContents = await reader.ReadToEndAsync();
}
Run Code Online (Sandbox Code Playgroud)

  • 那不应该是“StreamReader”而不是“StringReader”吗? (2认同)

Skr*_*ace 11

在你的控制器中:

  1. 检查是否IFormFile file包含某些东西
  2. 检查文件的扩展名是否是您要查找的扩展名 (.dat)
  3. 检查文件的 Mime 类型是否正确以避免攻击

然后,如果没问题,调用一个服务类来读取你的文件。

在您的服务中,您可以执行以下操作:

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)

希望能帮助到你。