当前位置:编程学习 > asp >>

在asp.net mvc中的上传

1.         Model层用一个TestModel
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
    {
        public ActionResult View1()
        {
            return View();
        }
        /// <summary>
        /// 提交方法
        /// </summary>
        /// <param name="tm">模型数据</param>
        /// <param name="file">上传的文件对象,此处的参数名称要与View中的上传标签名称相同</param>
        /// <returns></returns>
        [HttpPost]      
        public ActionResult View1(TestModel tm, HttpPostedFileBase file)
        {
            if (file == null)
            {
                return Content("没有文件!", "text/plain");
            }
            var fileName = Path.Combine(Request.MapPath("~/UploadFiles"), Path.GetFileName(file.FileName));
            try
            {           
                file.SaveAs(fileName);
                tm.AttachmentPath = fileName;//得到全部model信息
                return Content("上传成功!", "text/plain");
            }
            catch
            {
                return Content("上传异常 !", "text/plain");
            }        
        }
}
3.         View层:
@model UploadFile.Models.TestModel
@{
    Layout = null;
}
<!DOCTYPE html>
<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>普通上传</title>
</head>
<body>
    @*enctype= "multipart/form-data"是必需有的,否则action接收不到相应的file*@
    @using (Html.BeginForm("View1", "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>
        <input id="ButtonUpload" type="submit" value="提交" />
    }
</body>
</html>
这个页面是在提交时同时上传文件和提交数据。在action中,先把文件保存在服务器端,然后把服务端的路径赋给TestModel中的AttachmentPath属性,以便后台处……

 

补充:Web开发 , ASP.Net ,
CopyRight © 2022 站长资源库 编程知识问答 zzzyk.com All Rights Reserved
部分文章来自网络,