ASP.NET MVC Upload file

ASP.NET MVC Upload file – Đoạn mã dưới đây hướng dẫn cách upload file trong ASP.NET MVC

Entity class

public class FileInformation
{
public string FileName { get; set; }
public string CreatedDate { get; set; }
}

Controller

public ActionResult Upload()
{
return View();
}
[HttpPost]
public ActionResult Upload([Bind(Include =”FileName,CreatedDate”)] FileInformation file,
HttpPostedFileBase File1)
{
string path = Server.MapPath(“~/Uploads/”);

//Lấy phần mở rộng của file
string extensionName = System.IO.Path.GetExtension(File1.FileName);
// Tạo tên file ngẫu nhiên
string finalFileName = DateTime.Now.Ticks.ToString() + extensionName;
// Upload file lên server
File1.SaveAs(path + finalFileName);

//Làm gì đó với thông tin của file – lưu đường dẫn vào csdl chẳng hạn
file.FileName = finalFileName;
file.CreatedDate = DateTime.Today.ToShortDateString();
ViewBag.FileInfor = file;
return View(“Uploaded”);
}

Hiển thị thông tin file sau upload

@{
ViewBag.Title = “Uploaded”;
}
@{
var fi = (RoleBasedSecurityMVC5.Models.FileInformation)ViewBag.FileInfor;
}

<h2>Uploaded – File Information</h2>
<hr/>
<h3>File name: @fi.FileName</h3>
<h3>Created Date: @fi.CreatedDate</h3>

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s