首页 > Web开发 > 详细

ASP.NET MVC文件上传简单示例

时间:2021-07-02 15:19:32      阅读:23      评论:0      收藏:0      [点我收藏+]

一. 前端代码

 @using (Html.BeginForm("UploadFile", "Home", FormMethod.Post, new {enctype = "multipart/form-data"}))
        {
            <div>文件上传:<input type="file" name="myFile"/></div>
            <input type="submit" value="提交"/>
        }

 

二. 后端代码

        /// <summary>
        /// 上传文件
        /// </summary>
        /// <returns>上传文件结果信息</returns>
        [HttpPost]
        public ActionResult UploadFile()
        {
            HttpPostedFileBase file = Request.Files["myFile"];
            if (file != null)
            {
                try
                {
                    //检查是否存在文件夹
                    string subPath = "D:\\pic";
                    if (false == System.IO.Directory.Exists(subPath))
                    {
                        //创建pic文件夹
                        System.IO.Directory.CreateDirectory(subPath);
                    }                                  
                    var filename = Path.Combine("D:\\pic", file.FileName);  //Path.Combine(Request.MapPath("~/Upload"), file.FileName); MapPath:虚拟目录
                    file.SaveAs(filename);
                    return Content("上传完成");
                }
                catch (Exception ex)
                {
                    return Content(string.Format("上传文件出现异常:{0}", ex.Message));
                }

            }
            else
            {
                return Content("没有文件需要上传!");
            }
        }

 

ASP.NET MVC文件上传简单示例

原文:https://www.cnblogs.com/paopaotang/p/14962342.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!