1

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.

Mojack
  • 134
  • 2
  • 12
  • Related post - [MVC 6 HttpPostedFileBase?](https://stackoverflow.com/q/29836342/465053) – RBT Sep 21 '21 at 11:30

1 Answers1

5

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())
{
    ...
}
Chris Pratt
  • 232,153
  • 36
  • 385
  • 444
  • Oh wow. I named the variable of IFormFile simply "file", not "test". Now it works. Thanks! – Mojack Aug 02 '18 at 16:51
  • 1
    No problem. The param name doesn't *always* matter, but if you're posting something directly to a param, then the name does matter. – Chris Pratt Aug 02 '18 at 16:53