darewreck
darewreck

Reputation: 2614

How to upload file to stream from swagger?

I was wondering how you would generate the swagger UI to upload a file as a stream to the ASP.net Core controller.

Here is a link describing the difference between uploading small files vs. big files.

Here is the link of describing how to implement the upload for a small file, but doesn't elaborate on how to implement a stream.

https://www.janaks.com.np/upload-file-swagger-ui-asp-net-core-web-api/

Thanks, Derek

Upvotes: 3

Views: 2314

Answers (1)

ne1410s
ne1410s

Reputation: 7082

I'm not aware of any capability to work with Stream type(s) on the request parameters directly, but the IFormFile interface stipulates the ability to work with streams. So I would keep the IFormFile type in your request params, then either:

  • Copy it in full to a memory stream OR
  • Open the stream for read

In my case I wanted the base 64 bytes in full (and my files are only a few hundred kbs) so I used something like this:

string fileBase64 = null;
using (var memStream = new MemoryStream())
{
    model.FormFile.CopyTo(memStream);
    fileBase64 = Convert.ToBase64String(memStream.ToArray());
}

The MemoryStream is probably not appropriate in your case; as you mentioned large files which you will not want to keep in memory in their entirety.

So I would suggest opening the stream for reading, e.g.:

using (var fileStream = model.FormFile.OpenReadStream())
{
    // Do yo' thang
}

Upvotes: 1

Related Questions