[英]How can I read a file which will be upload from a form in .Net Core API?
我在 my.Net Core API 中创建了一个方法,它将上传一个文件。
[HttpPost]
public async Task<IActionResult> ReadFile(IFormFile file)
{
return BadRequest(file);
}
我做了一个return BadRequest(file)
以便阅读它在postman上发送给我的内容。
结果是这样的:
{
"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"
}
我在 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);
}
但是用户必须选择一个文件来读取它,应用程序不必进入文件夹并读取文件。
有可能这样做吗? 我可以有一些链接来帮助我做到这一点吗?
更新
我想要方法 ReadFile 读取我的文件的内容,这些内容将被上传到一个表单中。
所以我将有一个字符串,其中包含我的文件的内容,之后我将可以在此文件中执行所有我想做的事情。
例如,我有一个文件,在这个文件中写着LESSON ,使用ReadFile方法,我将在字符串中得到单词 lesson 。
该文件将绑定到您的IFormFile
参数。 您可以通过以下方式访问流:
using (var stream = file.OpenReadStream())
{
// do something with stream
}
如果您想将其作为字符串读取,则需要一个StreamReader
实例:
string fileContents;
using (var stream = file.OpenReadStream())
using (var reader = new StreamReader(stream))
{
fileContents = await reader.ReadToEndAsync();
}
在你的控制器中:
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();
希望能帮助到你。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.