Earlier working with
ASP.NET Web Forms we had File Upload control but in MVC we don't have Event Driven Programming or server side control.
For that I have created 1 table Products as in the following screen.
You can also create a table by running below script in SQL.
- /****** Object: Table [dbo].[Products] Script Date: 20-03-2016 15:11:31 ******/
- SET ANSI_NULLS ON
- GO
-
- SET QUOTED_IDENTIFIER ON
- GO
-
- CREATE TABLE [dbo].[Products](
- [ProductId] [int] IDENTITY(1,1) NOT NULL,
- [ProductName] [nvarchar](250) NULL,
- [FilePath] [nvarchar](250) NULL,
- CONSTRAINT [PK_Products] PRIMARY KEY CLUSTERED
- (
- [ProductId] ASC
- )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
- ) ON [PRIMARY]
-
- GO
Step 1: Create a MVC Application, select MVC Template and click on Ok.
Step 2: Bind with Model, for that right click on project, Add, then
ADO.NET Entity Data Model.
Choose EF Designer from database, here we are choosing Model Contents and click on OK.
Connect with your SQL Server, just enter the SQL Server credentials and choose your table from the list and click OK. it will create a connection string in web.config file.
Step 3: Build your application now, and go to Controller and add new controller.
Choose MVC 5 Controller with view using Entity framework.
Select
Product as Model Class and EMPEntities as a Data Context class and click on Ok.
Step 4 : This will create a Products folder in Views. Let's open Create.cshtml file and add the following code in Html.BeginForm section.
Here we are providing Parameter like Method name, Controller name, Method = Post and for File Uplaod enctype = "multipart/form-data"
The important thing here is additional form attributes 'multipart/form-data. This will send your additional form data (Ex. :file data) and make sure your file got uploaded when you post the page.
- @using (Html.BeginForm("Create",
- "Products",
- FormMethod.Post,
- new { enctype = "multipart/form-data" }))
For file upload control make sure you have input box and set type ="file" just shown in above screen.
- <input type="file" name="file" id="file" /><br><br>
Step 5: All set in View, now open your ProductController and make the changes in Create Method,
Remove Bind Parameter and for file upload just add HttpPostedFileBase file.
- public ActionResult Create([Bind(Include = "ProductId,ProductName,FilePath")] Product product)
Replace above line with the following code.
- public ActionResult Create(Product product, HttpPostedFileBase file)
Now set the file path as:
- string path = Path.Combine(Server.MapPath("~/Images"), Path.GetFileName(file.FileName));
- file.SaveAs(path);
And then
db.Products.Add change the parameter shown as per the following code snippet. Basically, we are storing the file path and upload the selected file in to Images folder. Please don't forget to create '
Images' folder in your application.
- if (ModelState.IsValid)
- {
- string path = Path.Combine(Server.MapPath("~/Images"), Path.GetFileName(file.FileName));
- file.SaveAs(path);
- db.Products.Add(new Product
- {
- ProductId = product.ProductId, ProductName = product.ProductName, FilePath = "~/Images/" + file.FileName
- });
- db.SaveChanges();
- return RedirectToAction("Index");
- }
Also you have to include the following reference in your controller.
Step 6: To display the image in your Index List view, just add image tag as:
- <img src="@Url.Content(item.FilePath)" alt="Image" height="50" width="50" />
@Url.Content(item.FilePath) will display the uploaded file.
That's it! Now run your application and add a new product and upload image.
Go to
Index page and check the file, which you have uploaded it displays here.
And this file you can check in your
Images folder in your application.
Hope you like this article on how to upload files in MVC, in the next article we will learn how to store images or files in database as a binary data in MVC.
Read more articles on ASP.NET: