Home / ASP.NET - MVC / Upload Files

Create an MVC application

Open Visual Studio. Go to File->New->Project. Name the application UploadFile. Click OK.

Select MVC Template. Click OK.

Add folder

We will add a folder to save files in the application

Add Controller

Right click Controller. Add->Controller.

Select MVC 5 Controller -Empty. select Add.

Rename the controller to Upload.

Write code in the following controller:

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace FileUpload.Controllers
{
    public class UploadController: Controller
    {
        // GET: Upload
        public ActionResultIndex()
        {
            return View();
        }
        [HttpGet]
        public ActionResult UploadFile()
        {
            return View();
        }
        [HttpPost]
        public ActionResult UploadFile(HttpPostedFileBase file)
        {
            try. try
            {
                if (file.ContentLength > 0)
                {
                    string _FileName = Path.GetFileName(file.FileName);
                    string _path = Path.Combine(Server.MapPath("~/UploadedFiles"), _FileName);
                    file.SaveAs(_path);
                }
                ViewBag.Message = "File Uploaded Successfully!!";
                return View();
            }
            catch. catch
            {
                ViewBag.Message = "File upload failed!!";
                return View();
            }
        }
    }
}

Add View

Right click on UploadFileActionResult. Select Add View.



Select the empty template. Click add.



Vietnamese code in the following view:

@{
    ViewBag.Title = "UploadFile";
}

UploadFile

@using(Html.BeginForm("UploadFile","Upload", FormMethod.Post, new { enctype="multipart/form-data"})) {
@Html.TextBox("file", "", new { type= "file"})
@ViewBag.Message
}

Ctrl+F5 run application

Is the application running well?

Click upload. We run debug to see if the file is successful

code is working as expected, as it appears the success message. We should also receive this message on View.

Open the folder containing the successfully uploaded file

Did you find this article helpful?

Support the author so they can write more quality articles!

Tư vấn lộ trình CNTT 🤖