Mojack
Mojack

Reputation: 144

Get file from Request over .NET Core Api

I don't know, how I can get the file over my .NET Core API and save it as a file.

For example: I upload my test file with the following method:

private void Button_Click(object sender, RoutedEventArgs e) {
        var client = new RestSharp.RestClient("https://localhost:44356/api/");

        var request = new RestSharp.RestRequest("Upload", RestSharp.Method.POST);
        request.AddFile(
            "test",
            "c:\\kill\\test.wav");

        client.Execute(request);
    }

And my API receives a request. This method looks like this:

[HttpPost]
    public IActionResult UploadFile() {
        using(var reader = new StreamReader(Request.Body)) {
            var body = reader.ReadToEnd();
        }
        return View();
    }

My body variable contains this:

-------------------------------28947758029299 Content-Disposition: form-data; name="test"; filename="test.wav" Content-Type: application/octet-stream RIFF^b

And now my question:

How can I get the file and save it on my disc?

I use .NET Core 2.1 Webapi & on my Client Restsharp version 106.3.1.

Upvotes: 1

Views: 8765

Answers (1)

Chris Pratt
Chris Pratt

Reputation: 239270

First, you need to determine how you want to send the file, i.e. the encoding type. That determines how the request body is interpreted. If you want to use multipart/form-data, then your action signature needs to look like:

public IActionResult UploadFile(IFormFile test) { // since you made the key "test"

Then, you can get the actual file data via either:

byte[] bytes;
using (var ms = new MemoryStream())
{
    await test.CopyToAsync(ms);
    bytes = ms.ToArray();
}

Or, if you want to utilize the stream directly:

using (var stream = test.OpenReadStream())
{
    ...
}

Upvotes: 5

Related Questions