asp.net mvc 文件上传,正在投入使用

先引入文中所用的文件,下载地址为:

https://download.csdn.net/download/xuejunling/10360702

引入两个js, 一个样式

View:

@{
    Layout = null;
}





    
    
    
    @**@
    
    


    @using (Ajax.BeginForm("UpLoadLogo_Post", "Default",
    new { },
    new AjaxOptions
    {
        HttpMethod = "POST",
        InsertionMode = InsertionMode.Replace,
        AllowCache = false
    }, new { enctype = "multipart/form-data", id = "myForm" }))
    {
        
@Html.TextBox("file", "", new { type = "file", required = "required", multiple = "multiple",style="width:200px;" })
}
后台:
[HttpGet]
        public ActionResult UpLoadLogo(string id)
        {
            return View();
        }

[HttpPost]
        public ActionResult UpLoadLogo_Post()
        {
            if (Request.Files != null && Request.Files.Count > 0)
            {
                float contextlength = 1024 * 1024 * 3;
                float.TryParse(upload_contentlength, out contextlength);
                HttpPostedFileBase file = Request.Files[0];
                if (file.ContentLength == 0)
                {
                    return Json(new { Error = 1, Message = "请选择上传的文件!" });
                }
                if (file.ContentLength > contextlength)
                {
                    return Json(new { Error = 1, Message = "上传文件过大,不能超过" + contextlength / (1024 * 1024 * 1.0) + "M!" });
                }
                string extension = System.IO.Path.GetExtension(file.FileName);
                string oldfilename = Path.GetFileName(file.FileName);

                string now = DateTime.Now.ToString("yyyyMMdd");
                string guid = Guid.NewGuid().ToString("N");
                Random r = new Random();
                int n = r.Next(1000, 9999);
                string newfilename = string.Concat(guid, n, extension);
                string dirpath = string.Format("/{0}/{1}", upload_userlogo, now);
                if (!Directory.Exists(Server.MapPath(dirpath)))
                {
                    Directory.CreateDirectory(Server.MapPath(dirpath));
                }
                string uploadfilepath = Path.Combine(Server.MapPath(dirpath), newfilename);
                file.SaveAs(uploadfilepath);

//IsAllowedExtension判断文件是否是真实的图片文件,如果是上传成功,如果不是,则删除
//特别提示:为了安全,服务器的上传文件夹,一定要去除执行脚本的权限,这样即使上传了木马程序,也不能运行,具体操作,可以网上搜索一下,这里简单提供一下如何做,把上传图片所在的文件夹里新建一个web.config文件,里面写入以下内容即可。


    
        
    

以上是小插曲,为了安全,还是重视点好。
                if (IsAllowedExtension(uploadfilepath))
                {
                    string filepath = dirpath + "/" + newfilename;
                    return Json(new { Error = 0, Data = filepath });
                }
                else
                {

                    if (System.IO.File.Exists(uploadfilepath))
                    {
                        System.IO.File.Delete(uploadfilepath);
                    }
                    return Json(new { Error = 1, Message = "请上传jpg,png,gif等类型的图片!" });
                }
            }
            else
            {
                return Json(new { Error = 1, Message = "请选择要上传的图片!" });
            }
        }

//检测真实图片格式。
 public static bool IsAllowedExtension(string path)
        {
            System.IO.FileStream fs = new System.IO.FileStream(path, System.IO.FileMode.Open, System.IO.FileAccess.Read);
            System.IO.BinaryReader r = new System.IO.BinaryReader(fs);
            string fileclass = "";
            byte buffer;
            try
            {
                buffer = r.ReadByte();
                fileclass = buffer.ToString();
                buffer = r.ReadByte();
                fileclass += buffer.ToString();

            }
            catch
            {

            }
            r.Close();
            fs.Close();
//说明255216是jpg;7173是gif;6677是BMP,13780是PNG;7790是exe,8297是rar  
            if (fileclass == "255216" || fileclass == "7173" || fileclass == "13780")
            {
                return true;
            }
            else
            {
                return false;
            }

        }

其中:
upload_contentlength :设定的上传文件的大小。
upload_userlogo: 上传文件放置的文件夹。

你可能感兴趣的:(Asp.Net,Jquery,JS)