简体   繁体   中英

How can I read a file which will be upload from a form in .Net Core API?

I create a method in my.Net Core API which will upload a file.

[HttpPost]
public async Task<IActionResult> ReadFile(IFormFile file)
{
    return BadRequest(file);
}

I do a return BadRequest(file) in order to read what it send me on postman .

The result is this:

{
    "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"

}

I see on Microsoft documentation this:

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);
}

But the user will have to choose a file to read in it, the application won't have to go in a folder and read a file.

It is possible to do this? And can I have some link to help me to do this?

Update

I want to the method ReadFile read the content of my file which will be upload thinks to a form.

So I will have a string which will have the content of my file and after that I will can all I wanted to do in this file.

For example I have a file and in this file it is wrote LESSON , with the method ReadFile I will get the word lesson in a string.

The file will be bound to your IFormFile param. You can access the stream via:

using (var stream = file.OpenReadStream())
{
    // do something with stream
}

If you want to read it as a string, you'll need an instance of StreamReader :

string fileContents;
using (var stream = file.OpenReadStream())
using (var reader = new StreamReader(stream))
{
    fileContents = await reader.ReadToEndAsync();
}

In you Controller:

  1. Check if IFormFile file contains something
  2. Check if the file's extension is the one you are looking for (.dat)
  3. Check if the file's Mime type is correct to avoid attacks

Then, if it is all right, call a Service class to read your file.

In your Service, you can do something like that:

var result = new StringBuilder();
using (var reader = new StreamReader(file.OpenReadStream()))
{
    while (reader.Peek() >= 0)
        result.AppendLine(await reader.ReadLineAsync()); 
}
return result.ToString();

Hope it helps.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM