File upload in asp net core mvc

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
they say is part 53 of asp.net core tutorial in this video we'll discuss how to upload a file in asp.net core MVC with an example here is what we want to do on our create employee form we want to include a field for photo using this file upload control the user will be able to select a photo that he wants to upload onto the server when this form is submitted we want to store employee name email Department and the photo path in the underlying employees table but the photo itself should be uploaded onto the server into this images folder if we take a look at of a create view at the moment the model for this view is our employee class but we are not going to use this employee class as the model we are going to create a view model that is specific to this create view we'll understand the reason for that in just a bit but first to this view models folder let's add a new class file name the file employee create view model the properties in this class are going to be very similar to what we already have in our employee class so let's copy over and then change the bits that are required at the moment we don't need this ID property in our view model class so let's get rid of that first and then let's bring in the require namespace for these validation attributes de BD e Nome is present in employee management dot models namespace so let's bring that in as well here is the important bit to understand let's change the name of this property from photo path to just photo and the data type of this is a form file this type is in Microsoft dot asp net core dot HTTP namespace so let's bring that namespace in if you're wondering why did we set the data type of the photo property within our view model class to iPhone file well that's because the file that is uploaded to the server can be accessed through model binding using this interface I form file as you can say this iPhone file interface has got a lot of useful properties like content type header length file name and then a few other methods we're not going to use all these properties and methods just going to use the file name property and then this copied to method to copy the photo into the images folder on our web server now coming back to the question why did we create a separate view model for our create view well that's because to be able to access the uploaded file on the server through model binding we need a property with this type I phone file at this point you could argue we could easily do that on this employee class as well just change the data type of this photo path property to I form file well if we do that we have to create a navigation property because iPhone file is a complex object and creating a navigation property could complicate things further on top of that we don't want to store all this information about the uploaded file in the underlying data base we just want to store the name of the file in the underlying employees table so to keep things simple and take this example quickly forward we have set the data type of the photo path property to string on the employee model class in this class corresponds to the employee's table and then on this view model class for our create view we have included photo property with this type by form file so we could receive the uploaded file on the server and access it through model binding at the moment the model for our create view is still employee let's change this to our new type employee create view model we don't need this employee repository injected into our create view anymore so let's delete that and we also don't need this code right here so let's delete this as well at the moment on our create employee form we only have fields to capture employee name email and Department we also need a field to be able to upload employee photo it's going to be similar to one of these fields so let's copy the email field HTML and then change the beds that are required the label here is for photo property within our view model class so let's change the property name here to photo even on the input element we want to change this from email to photo this placeholder attribute is not required to style this file upload control properly in addition to form control bootstrap CSS class we also need custom file input class we are not performing any validation so let's delete the span element we need a label and for styling let's use custom file label bootstrap class we want the text choose file in the file upload control again for proper styling let's wrap the input element and the label with a development and then use the bootstrap class custom file to support file upload using this form we have to set the form element and type attribute to multi-part slash form data at this point let's save our changes and take a look at the browser notice when I reload this page we have the file upload control as expected now one question you might have at this point is nowhere in the HTML we have specified that we want an input element whose type is file when we said the input element type to file then we get the file upload control here we are not specified that we want an input element whose type is file but how did we get this file upload element well that's because on the input element yes at SB - for tag helper - the photo property and if you look at the photo property its data type is iPhone file so asp.net core knows if the datatype of the property to which we are binding is iform file then it has to provide us with file upload control and that's how we got this file upload control now if we inspect the page source notice the input element type is set to file at the moment we have a small issue with the file upload control notice when I select a file to upload notice we don't see the file that we have just selected but when I hover the mouse over that's when I see from the tool there we have selected a file with name David dot PNG but the file upload control itself does not display that selected file to fix this we have to write a couple of lines of custom jQuery code now if we take a look at our layout view notice we have a custom section here called scripts we are going to use this section to inject the JavaScript that we need so in our create view just before the closing form tag let's include a section the name of the section is script we won't write some JavaScript code so let's include the script element and when the document is ready we want to execute some JavaScript code what we are writing here is jQuery code if you are new to jQuery I suggest please check out our jQuery course it starts from the basics and covers all the concepts you need in the interest of time I'm going to base the required jQuery code and quickly walk you through the first thing that we are doing here is selecting the HTML element that has the class custom file input we're using the jQuery class selector here this is going to select our file upload control because this is the input element that has the class custom file input once we have the file upload control selected we are binding to its change event whenever the text in the file upload control changes we want this code to be executed so when a file is collected its text changes and this code will be executed and the line right here selects the name of the file that we have selected in the file upload control so once we have the file name we want to display that file name using this label that is present next to the file upload control so to select this label we are again using the jQuery class selector so select the element that has this class custom file label and this is the label that has that class and then we are displaying the file name using that label let's save these changes and take a look at browser notice now when we select a file we see the selected file in the file upload control when we sum in this form by clicking the create button within our home controller this is the create action method that handles the posted form now if we take a look at our create view notice the model for this view is employee create view model so within our home controller for this create action method let's change the parameter type to employee create view model and let's name this parameter model if the model state is valid the first thing that I'm going to do here is create a variable of type string let's call it unique file name and then initialize this to now on the incoming model object whose type is employee create view model we have a property photo and this property receives the uploaded file so we want to check if the photo property on the model object is not now if the photo property is not null that means the user has selected a file to upload and we want to upload that file to the images folder in www told to get the physical path of this www root folder we are going to use a hosting environment service provided by asp.net core so let's inject a hosting environment service into the home controller using its constructor let's bring in the required namespace and name this parameter hosting environment and let's use Visual Studio to generate the private field on this I hosting environment service we have web route path property this provides us the absolute physical part of this www.fortuigence.com bine the path string of this www root folder with this images folder for that let's use the path class this class is present in system dot IO namespace let's bring in the namespace and then use combined method to combine the path string of www.fortuigence.com the intellisense the combined method returns the path to the images folder as a string so let's store it in a variable of type string I'm going to name this variable uploads folder we want the file names in the images folder to be unique if we upload two files with the same name one file may override the other we don't want that to happen to ensure we have unique file names I'm going to use grid class QuIDD stands for global unique identifier every time we call this new grid method it returns a new grid which is guaranteed to be unique let's convert this to a string to this let's append an underscore and to that we want to append the uploaded file name to get to the uploaded file name we use the incoming model object on that we have the photo property and on that we have file name property let's store this unique name in this variable at this point we have the path to the uploads folder and the file name itself let's combine them together using path dot combined let's store this combined part in a variable of type string I'm going to call this variable file path now to copy the uploaded file to the images folder we aren't going to use this copy to method provided by this iform file interface remember the photo property on our model object is of type I form file and this property receives the uploaded file this means on a model object on this photo property we can use this copy to method to copy the uploaded file to the images folder notice on the incoming model object we have photo property and on this property we have copied to method we need a new file stream to copy the contents of the uploaded file so let's create a new file stream and the file stream itself needs the path to the file and we have the path to the file in this variable so let's pass this variable to the file stream constructor and then we want this file to be created on the server so let's set the file mode to create at this point we have at the uploaded employee photo copied into the images folder on our server now we need to create a new employee object and then copy the employee related properties from the incoming model object into this new employee object name equals model dot name email equals model dot email Department equals model dot Department and finally photo path equals we have the photo part present in this variable unique file name at this point we want to save this new employee object in the underlying employee's database table for that we are going to use this injected I employee repository on the repository we have add method to that let's pass the employee object after the employee is successfully saved to the database table we want to rewrite the user to the detail section so we could see the details of that newly added employee so let's uncomment this line remember after entity framework inserts a new row for this new employee object in the underlying employees table it takes the ID column generated identity value and automatically updates the ID property on our employee object we are then passing that ID value to the detail section so we could see the details of that newly added employee let's fill out the details of the new employee that we want to add click the Browse button let's select this photo david dot PNG and then click the Create button there we go of a new employee is created and we are redirected to the details view and we see the details of the new employee that we have just created but we still see the old image we don't see the image that we have uploaded first let's open the images folder in File Explorer notice we have the image that we have just uploaded we see a grid and underscore and then the name of the file david dot B and E but this details view does not display that uploaded image that's because we have hard-coded the image source element to always display no image dot jpg so let's change the code in our details view let's go to the views folder and open details view notice the source attribute of our image element is hard-coded to know image dot jpg we want to dynamically set the source attribute for that I'm going to create a variable let's name the variable for the path all our employee photos are in the images folder and the images folder is in the Buda Buda be root folder to get to the root folder we used Tilda that we have our images folder to that we want to append the name of the image to get the name of the image we can use the model object to get to the model object we use back model and on that we have employee property and on the employee property we have photo path what if an employee does not have this photo path property said if we look at the existing data notice for the two existing employees Mary and John the photo path property is now it's only sad for this new employee David that we have just created so if the photo path property is null we want to display no image dot jpg this expression in the brackets is evaluated first if the photo path property is not now then that value is used if it is null then no image dot jpg is used so instead of hard-coding the source attribute always - no image dot jpg let's use the value that we have in this variable photo path we have the same issue in our index view as well notice even here the source attribute is hard-coded to know image dot jpg the change is going to be very similar to what we already have in our details view so let's make a copy of this line paste it and then change the bits that are required the model for this view is ienumerable of employee objects we're using the for each loop here to loop through each employee object we have in the model to check the photo path property of each employee object we want to use this loop variable employee finally let's use this variable photo path as the value for the source attribute notice now when I reload the page we don't see any image to get this working use SP - append version attribute on the image element on our details view notice now when we reload the page we see the image as expected we are using image tag helper here which provides cache busting service if you're new to image tag helper please check out part 37 of our asp.net core tutorial now when we navigate to the list view notice the images have different heights and widths to set all these images to the same height in width I'm going to include a custom CSS class so let's open our site dot CSS file our site dot a CSS file is in the CSS folder i'm going to name the CSS class image thumbnail set height to 200 pixels width to auto now let's use the CSS class on the image element in our index view now hard reload the page by pressing ctrl shift our notice all the images have the same height in width now at this point let's create another new employee fill the details of the new employee let's select sarah dot PNG click create there we go we have our new employee created we see all the employee details including the photo that we uploaded now let's navigate to the list view notice all the four employees are in this one row if we add another new employee that employee will also be placed in this one row further squeezing these thumbnails what we want to do is include a maximum of three thumbnails in a given row there are several ways to do this in the interest of time I'm going to take the quickest and easiest approach on this bootstrap card div I'm going to include this custom style I'm setting the minimum width to 18 gram and maximum width to 30.5% let's save our changes and take one final look at Roza notice now when we reload the page we see a maximum of three thumbnails Perl now let's create another new employee this time I'm not going to select any image for this employee let's click create notice the employee is created and it is using the default no image dot jpg if we navigate to the list view we see of a new employee here and even on the list view it's using no image dot jpg if we refresh the data that we have in our employees table notice we see all the employees both David and Sarah have a photo we created Ben without uploading a photo so the photo path property is now that's it in this video thank you for listening you [Music]
Info
Channel: kudvenkat
Views: 131,679
Rating: undefined out of 5
Keywords: asp.net core mvc file upload, asp.net core file upload example, asp.net core file upload api, asp.net core file upload model binding, asp.net core file upload controller, asp.net core upload file form, asp.net core how to upload file, asp.net core upload file iformfile, asp.net core file upload javascript, asp net core file upload with model, asp.net core upload file to server, asp.net core upload file to wwwroot
Id: aoxEJii70_I
Channel Id: undefined
Length: 23min 11sec (1391 seconds)
Published: Wed May 08 2019
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.