ASP.NET - MVC - Upload Files

Tạo một ứng dụng MVC 

Mở Visual Studio. Go to File->New->Project. Đặt tên ứng dụng là UploadFile. Click OK.

Chọn MVC Template. Click OK.

Thêm thư mục 

Chúng ta sẽ thêm thư mục để lưu tập tin trong ứn dụng

Thêm Controller

 Click chuột phải  Controller. Add->Controller.

Chọn MVC 5 Controller -Empty. chọn Add.

Đặt lại tên controller là Upload.

Viết code trong controller sau:

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 ActionResult Index()
        {
            return View();
        }
        [HttpGet]
        public ActionResult UploadFile()
        {
            return View();
        }
        [HttpPost]
        public ActionResult UploadFile(HttpPostedFileBase file)
        {
            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
            {
                ViewBag.Message = "File upload failed!!";
                return View();
            }
        }
    }
}

 

Thêm View

Click chuột phải vào UploadFileActionResult. Chọn Add View.



Chọn template rỗng. Click add.



Việt code trong view sau:

@{
    ViewBag.Title = "UploadFile";
}
<h2>UploadFile</h2>
@using(Html.BeginForm("UploadFile","Upload", FormMethod.Post, new { enctype="multipart/form-data"}))
{
    <div>
        @Html.TextBox("file", "", new {  type= "file"}) <br />
        <input type="submit" value="Upload" />
        @ViewBag.Message
    </div>
}

 

Ctrl+F5 chạy ứng dụng

Việc chạy ứng dụng có tốt hay chưa?

Click upload. Chúng ta chạy debug xem file có thành công

code đang hoạt động như mong đợi, khi nó xuất hiện thông báo thành công. Chúng ta cũng nên nhận được thông báo này trên View.

Mở thư mục nơi chứa tập tin được upload thành công