[英]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.