Source: http://www.cnblogs.com/zhouhb/p/3906714.html
Recently, I've learned how ASP. NET MVC uploads files by referencing network data. Most basic, not with jquery and other technologies.
1. Define Model
public class Testmodel
{
[Display (Name = "title")]
[Required]
public string Title
{
Get
Set
}
[Display (Name = "content")]
[Required]
[DataType (Datatype.multilinetext)]
public string Content
{
Get
Set
}
public string AttachmentPath
{
Get
Set
}
}
2. Controller
1234567891011121314151617181920212223242526272829303132333435363738394041 |
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>
<title>普通上传</title>
<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>
|
3.2 show.cshtml
@model MvcApplication1.Models.TestModel
@{
ViewBag.Title =
"Show"
;
}
@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 />
图片:
"@Model.AttachmentPath"
alt=
"img"
/>
ASP. NET MVC upload file