Uploading a file from a website is pretty simple, but I always have to look it up. There’s all sorts of different technologies and frameworks that work with the web, so I just thought I would write down how I got it to work so that next time I can just come back here and say “oh, yeah, that’s how I did it…”
Front End
I’m using Angular for the front end, with Bootstrap for making the UI.
Picking a file
Bootstrap has some styling around the traditional file input that makes it look a little nicer, but the key is just an input tag with type=”file”.
In the component I have a File property that gets set to the result of the onFileChange event. Note that the UI is updated between ‘Choose File’ vs. the file name as soon as it is defined. In order to get the Browse button to match the theme, I’m using a little bit of CSS. Otherwise, the button looks like the typical/default gray button.
Uploading a file
Then, create a FormData and append the file to it. Use that FormData as the content in an http.post
Back End
I’m using ASP.NET Core for the back end.
The action will read the file from the form’s files into a MemoryStream, which we can then use to do whatever we want. In this example, I’m uploading a text file, so I just read the contents as text and send it over to another service for processing.
ASP.NET Core – Unit Testing a file upload – Darchuk.NET
[…] week I wrote about how to upload a file from a website using Angular and .NET Core. Writing tests for this is mostly straightforward, but there’s a few gotchas that I thought […]