標籤:blog http os io 檔案 資料 for ar
最近參考網路資料,學習了ASP.NET MVC如何上傳檔案。最基本的,沒有用jQuery等技術。
1、定義Model
public class TestModel
{
[Display(Name = "標題")]
[Required]
public string Title
{
get;
set;
}
[Display(Name = "內容")]
[Required]
[DataType(DataType.MultilineText)]
public string Content
{
get;
set;
}
public string AttachmentPath
{
get;
set;
}
}
2、Controller
public class TestController : Controller { // // GET: /Test/ public ActionResult Upload() { return View(); } /// <summary> /// 提交方法 /// </summary> /// <param name="tm">模型資料</param> /// <param name="file">上傳的檔案對象,此處的參數名稱要與View中的上傳標籤名稱相同</param> /// <returns></returns> [HttpPost] public ActionResult Upload(TestModel tm, HttpPostedFileBase file) { if (file == null) { return Content("沒有檔案!", "text/plain"); } var fileName = Path.Combine(Request.MapPath("~/Upload"), Path.GetFileName(file.FileName)); try { file.SaveAs(fileName); //tm.AttachmentPath = fileName;//得到全部model資訊 tm.AttachmentPath = "../upload/" + Path.GetFileName(file.FileName); //return Content("上傳成功!", "text/plain"); return RedirectToAction("Show",tm); } catch { return Content("上傳異常 !", "text/plain"); } } public ActionResult Show(TestModel tm) { return View(tm); } }
3、View
3.1 Upload.cshtml
@model MvcApplication1.Models.TestModel@{ ViewBag.Title = "Upload";}<!DOCTYPE html><html><head> <title>普通上傳</title></head><body> @*enctype= "multipart/form-data"是必需有的,否則action接收不到相應的file*@ @using (Html.BeginForm("Upload", "Test", FormMethod.Post, new { enctype = "multipart/form-data" })) { @Html.LabelFor(mod => mod.Title) <br /> @Html.EditorFor(mod => mod.Title) <br /> <br /> @Html.LabelFor(mod => mod.Content) <br /> @Html.EditorFor(mod => mod.Content) <br /> <span>上傳檔案</span> <br /> <input type="file" name="file" /> <br /> <br /> <input id="ButtonUpload" type="submit" value="提交" /> }</body></html>
3.2 Show.cshtml
@model MvcApplication1.Models.TestModel@{ ViewBag.Title = "Show";}<h2>Show</h2>@Html.LabelFor(mod => mod.Title)<br />@Html.EditorFor(mod => mod.Title)<br /> <br />@Html.LabelFor(mod => mod.Content)<br />@Html.EditorFor(mod => Model.Content)<br />圖片:<img src="@Model.AttachmentPath" alt="img" />