C#图片上传,并做安全检测

    xiaoxiao2021-03-25  180

    public void ProcessRequest(HttpContext context) { HttpPostedFile uploadFile = context.Request.Files["file"]; string fileName = Path.GetFileName(uploadFile.FileName); string newFileName; Stream stream = uploadFile.InputStream; byte[] fileByte = new byte[2]; stream.Read(fileByte, 0, 2); string fileFlag = ""; if (fileByte != null && fileByte.Length > 0) { fileFlag = fileByte[0].ToString() + fileByte[1].ToString(); } string[] fileTypeStr = { "255216", "13780" };//对应的图片格式jpg,png if (!fileTypeStr.Contains(fileFlag)) { stream.Close(); stream.Dispose(); context.Response.Write("error"); } else { if (Path.GetExtension(uploadFile.FileName).ToUpper() == ".JPG" || Path.GetExtension(uploadFile.FileName).ToUpper() == ".PNG") { newFileName = DateTime.Now.ToString("yyyyMMddHHmmssffff") + Path.GetExtension(uploadFile.FileName); } else { newFileName = DateTime.Now.ToString("yyyyMMddHHmmssffff") + ".jpg"; } string ImgServerPath = ConfigurationManager.AppSettings["ImgServerPath"]; string serverPath = ConfigurationManager.AppSettings["ServerPath"]; ImgServerPath = HttpContext.Current.Server.MapPath(ImgServerPath); if (!Directory.Exists(ImgServerPath)) { Directory.CreateDirectory(ImgServerPath); } string serverFilePath = ImgServerPath + newFileName; uploadFile.SaveAs(serverFilePath); stream.Close(); stream.Dispose(); context.Response.Write(ConfigurationManager.AppSettings["ServerPath"] + ConfigurationManager.AppSettings["ImgServerPath"] + newFileName); } context.Response.End(); }
    转载请注明原文地址: https://ju.6miu.com/read-2124.html

    最新回复(0)