ASP.NET MVC上传文件

时间:2022-08-29 12:35:38

最近参考网络资料,学习了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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
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"  />