Join Jess Chadwick for an in-depth discussion in this video Challenge: Process an uploaded image file, part of ASP.NET Core: Razor Pages.
- [Instructor] In this chapter, I showed you how to build a form using tag helpers and then process the data from that form on the server. However, my implementation had one hole that I actually pointed out. I didn't add the ability to upload an image, so the existing image got overwritten with a null value every time the form was posted back. Your challenge is to fix this problem for me by adding the ability to upload an image file as a property in the HTML form.
Also, this image should be optional, meaning you shouldn't have to select an image to upload every time you want to change one of the other fields. If an image is uploaded with the form, assign the bytes that were uploaded to the image property on the recipe object. If an image is not uploaded with the form post, just leave the existing image data, if any, alone. I've shown you everything you'll need to know in order to accomplish this task, except for the following tips.
In order to attach a file to an HTML form, you can use the input tag with a type, of file. Also, in order for the contents to be posted along with the HTML form data, the form's encoding type must be set to multipart/form-data, like this. On the server side, ASP.NET Core uses the type Microsoft.AspNetCore.Http.IFormFile to represent a posted file form field.
And finally, the most effective way to read the uploaded file contents, is to copy them to an instance of a MemoryStream and then read the contents of that stream as a byte array. You'll know that you've succeeded once you see the image in the recipe page after you've uploaded it. This challenge will probably take you about 10 minutes to complete. Good luck.
- Creating a new application
- Setting up pages
- Rendering dynamic content
- Reusing markup with layouts
- Increasing the maintainability of pages
- Processing data
- Validating input
- Securing an application