How to upload files or images using Asp.net MVC 6 with some model data? Example, I have a form like this;
<form>
<input type="file">
<input type="text" placeholder="Image name...">
<input type="text" placeholder="Image description...">
<input type="submit" value="Submit">
</form>
I read many Tutorials in how to upload but I don't see anything uploading with some data like the form above.
Also, is there any library for image manipulation for re-sizing and Image Watermarking same as Codeigniter image manipulation class? (https://codeigniter.com/user_guide/libraries/image_lib.html
You can add a new property of type
IFormFile
to your view modeland in your GET action method, we will create an object of this view model and send to the view.
Now in your Create view which is strongly typed to our view model, have a
form
tag which has theenctype
attribute set to"multipart/form-data"
And your HttpPost action to handle the form posting
If you want to upload the file to some directory in your app, you should use
IHostingEnvironment
to get the webroot path. Here is a working sample.This will save the file to
uploads
folder insidewwwwroot
directory of your app with a random file name generated using Guids ( to prevent overwriting of files with same name)Here we are using a very simple
GetUniqueName
method which will add 4 chars from a guid to the end of the file name to make it somewhat unique. You can update the method to make it more sophisticated as needed.Should you be storing the full url to the uploaded image in the database ?
No. Do not store the full url to the image in the database. What if tomorrow your business decides to change your company/product name from
www.thefacebook.com
towww.facebook.com
? Now you have to fix all the urls in the table!What should you store ?
You should store the unique filename which you generated above(the
uniqueFileName
varibale we used above) to store the file name. When you want to display the image back, you can use this value (the filename) and build the url to the image.For example, you can do this in your view.
I just hardcoded an image name to
imgFileName
variable and used that. But you may read the stored file name from your database and set to your view model property and use that. Something likeStoring the image to table
If you want to save the file as bytearray/varbinary to your database, you may convert the
IFormFile
object to byte array like thisNow in your http post action method, you can call this method to generate the byte array from
IFormFile
and use that to save to your table. the below example is trying to save a Post entity object using entity framework.My Action Is
you can try below code
1- model or view model
2- View page
3- Controller