关于MVC 上传文件

 前台代码如下

复制代码
@{
    Layout = null;
}

<!DOCTYPE html>

<html>
<head>
    <title>Index</title>
    <script src="@Url.Content("~/Scripts/jquery-1.5.1.min.js")" type="text/javascript"></script>
    <script type="text/javascript">
        var times = 1;
        $("#add").click(function () {
            var fileNmae = "FileUpLoad" + n;
            $("#divdivfile").append("<input type=\"file\" name=\"" + fileNmae + "\" />");
            times++;
        });
    </script>
</head>
<body>
    <div>
        @using (Html.BeginForm("UpLoad", "UpdateLoad", FormMethod.Post, new { enctype="multipart/form-data"}))
        { 
            <div id="divfile">
                <input type="file" name="FileUpload" />
            </div>
            <input type="button" id="add" value="增加" />
            <input type="submit" id="Submit" value="上传" />
        }
    </div>
</body>
</html>

复制代码

首先判断上传的文件是否合法

复制代码
    public enum FileTypeExtension
    {
        GIF = 7173,
        PNG = 13780,
        JPG = 255216,
    }
    public class FileUploadCommon
    {
        /// <summary>
        /// 主要用于判断上传的特定文件是否附合特定后缀名的限制
        /// </summary>
        /// <param name="fu">上传的文件对象</param>
        /// <param name="fileEx">系统允许上传的文件的类型</param>
        /// <returns>true:代表通过验证,false:代表没有通过验证</returns>
        public static bool IsAllowedExtension(HttpPostedFileBase fu, FileTypeExtension[] fileEx)
        {
            int contentLength = fu.ContentLength;
            byte[] buffer = new byte[contentLength];
            fu.InputStream.Read(buffer, 0, contentLength);
            MemoryStream input = new MemoryStream(buffer);
            BinaryReader reader = new BinaryReader(input);
            string s = "";
            try
            {
                s = reader.ReadByte().ToString();
                s = s + reader.ReadByte().ToString();
            }
            catch
            {
            }
            reader.Close();
            input.Close();
            foreach (FileTypeExtension extension in fileEx)
            {
                if (int.Parse(s) == Convert.ToInt32(extension))
                {
                    return true;
                }
            }
            return false;
        }

    }
复制代码

 

后台代码 分为 单个上传和批量上传,注示部份为批量上传

复制代码
[HttpPost]
        [ValidateInput(false)]
        public ActionResult UpLoad(FormModel model)
        {
            FileTypeExtension[] fileTypeArr = { FileTypeExtension.GIF, FileTypeExtension.JPG, FileTypeExtension.PNG };
            // 单个上传
            try
            {
                if (Request.Files != null && Request.Files.Count > 0 && Request.Files[0].ContentLength > 0)
                {
                    string fileType = Request.Files[0].FileName.Substring(Request.Files[0].FileName.LastIndexOf("."));   // 获取文件类型
                    Stream fileStream = Request.Files[0].InputStream;
                    bool fileOk = FileUploadCommon.IsAllowedExtension(Request.Files[0], fileTypeArr);    // 判断上传的文件是否合法
                    if (fileOk && Request.Files[0].ContentLength / 1024 < 1024)   // 判断合法 及 文件大小是否合法
                    {
                        string path = Server.MapPath("/Content/FileUpdateLoad/");
                        string fileName = Path.GetFileNameWithoutExtension(Request.Files[0].FileName) + DateTime.Now.ToString("yyyyMMddHHmmss") + fileType;
                        Request.Files[0].SaveAs(Path.Combine(path, fileName));
                        return RedirectToAction("Index", "UpdateLoad");
}
else ViewBag.Error = "文件过大或格式不正确"; } else ViewBag.Error = "上传文件失败,可能您未选择上传文件"; } catch (Exception ex) { ViewBag.Error = "上传文件失败,原因如下:" + ex.Message; } //foreach (string upload in Request.Files) // 如果是批量上传 //{ // if (upload != null && Request.Files[upload].ContentLength > 0) // { // string fileType = Request.Files[upload].ContentType; // 获取文件类型 // Stream fileStream = Request.Files[upload].InputStream; // bool fileOk = FileUploadCommon.IsAllowedExtension(Request.Files[upload], fileTypeArr); // 判断上传的文件是否合法 // if (fileOk && Request.Files[upload].ContentLength / 1024 < 1024) // 判断合法 及 文件大小是否合法 // { // string path = Server.MapPath("/Content/FileUpdateLoad/"); // string fileName = Path.GetFileNameWithoutExtension(Request.Files[upload].FileName) + DateTime.Now.ToString("yyyyMMddHHmmss") + fileType; // Request.Files[upload].SaveAs(Path.Combine(path, fileName)); // } // else // ViewBag.Error = "文件过大或格式不正确"; // } // else continue; //} return View(model);
}
复制代码

 

还可以通过以下方式:

复制代码
  [HttpPost]
        [ValidateInput(false)]
        public ActionResult UpdateLoad()
        {
            FileTypeExtension[] fileTypeArr = { FileTypeExtension.GIF, FileTypeExtension.JPG, FileTypeExtension.PNG };
            // 单个上传
            try
            {
                if (Request.Files != null && Request.Files.Count > 0 && Request.Files[0].ContentLength > 0)
                {
                    HttpRequest request = System.Web.HttpContext.Current.Request;
                    HttpFileCollection FileCollect = request.Files;
                    if (FileCollect.Count > 0&& FileCollect[0].ContentLength>0)          //如果集合的数量大于0
                    {
                        //foreach (string str in FileCollect)
                        //{
                        //    HttpPostedFile FileSave = FileCollect[str];  //用key获取单个文件对象HttpPostedFile
                        //    string imgName = DateTime.Now.ToString("yyyyMMddhhmmss");
                        //    string imgPath = "/" + imgName + FileSave.FileName;     //通过此对象获取文件名
                        //    string AbsolutePath = Server.MapPath(imgPath);
                        //    FileSave.SaveAs(AbsolutePath);              //将上传的东西保存
                        //    Response.Write("<img src='" + imgPath + "'/>");
                        //}
                        HttpPostedFile FileSave = FileCollect[0];  //用key获取单个文件对象HttpPostedFile
                        string fileName = Path.GetFileName(FileSave.FileName);
                        string imgName = DateTime.Now.ToString("yyyyMMddhhmmss") + FileSave.FileName;
                        bool fileOk = FileUploadCommon.IsAllowedExtension(Request.Files[0], fileTypeArr);    // 判断上传的文件是否合法
                        if (fileOk && FileSave.ContentLength / 1024 < 1024)   // 判断合法 及 文件大小是否合法
                        {
                            string AbsolutePath = Server.MapPath("/Content/FileUpdateLoad/" + imgName);
                            FileSave.SaveAs(AbsolutePath);              //将上传的东西保存
                            //int fileLength = FileSave.ContentLength;
                            //Byte[] fileByteArr = new Byte[fileLength];
                            //Stream fileStream = FileSave.InputStream;      // 创建文件读取流
                            //fileStream.Read(fileByteArr, 0, fileLength);
                            //localhost.WebService1 myService = new localhost.WebService1();
                            //myService.SaveFile(fileByteArr, fileLength, fileName);
                        }
                    }
                }

            }
            catch (Exception ex)
            {
                TempData["UploadError"] = "上传文件失败,原因如下:" + ex.Message;
            }
            return RedirectToAction("Index");
        }
复制代码

 

 

关于配置文件 限制上传文件大小 和上传时间

    <httpRuntime executionTimeout="5000" maxRequestLength="2048000" useFullyQualifiedRedirectUrl="false"/>
  </system.web>

 

posted @   酒沉吟  阅读(328)  评论(0编辑  收藏  举报
编辑推荐:
· AI与.NET技术实操系列:基于图像分类模型对图像进行分类
· go语言实现终端里的倒计时
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
阅读排行:
· 25岁的心里话
· 闲置电脑爆改个人服务器(超详细) #公网映射 #Vmware虚拟网络编辑器
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· 零经验选手,Compose 一天开发一款小游戏!
· 一起来玩mcp_server_sqlite,让AI帮你做增删改查!!
历史上的今天:
2012-08-07 c# asp.net中事物及SQLServer存储过程事物的运用
点击右上角即可分享
微信分享提示