昨天做了个根据文件头判断上传类型的静态类,结果今天跑到 uploadify 调用的时候,图片始终上传不成功,然后自己看了下,原来 ContentType 都一样,全是文件流,而不会根据扩展名变动
所以,只好再次修改代码,不废话了
App_Code/FileUpload.cs
using System;
using System.Collections.Generic;
using System.Drawing;
using System.IO;
using System.Text;
using System.Text.RegularExpressions;
using System.Web;
/// <summary>
/// FileHeader 的摘要说明
/// </summary>
public static class FileUpload
{
private static string script = string.Empty;
private static bool autonamed = true;
private static Random ra = new Random();
private static bool addmark = true;
private static string err = string.Empty;
public static bool AddWaterMark
{
get
{
return addmark;
}
set
{
addmark = value;
}
}
public static bool AutoNamed
{
get
{
return autonamed;
}
set
{
autonamed = value;
}
}
public static string Script
{
get
{
return "var upload = [" + script + "];";
}
}
public static Dictionary<string, object> FilesHeader = new Dictionary<string, object>();
public static string[] txtType = new string[] { "txt", "xml", "css" };
static FileUpload()
{
FilesHeader.Add("gif", new byte[] { 71, 73, 70, 56, 57, 97 });
FilesHeader.Add("bmp", new byte[] { 66, 77 });
FilesHeader.Add("jpg", new byte[] { 255, 216, 255 });
FilesHeader.Add("png", new byte[] { 137, 80, 78, 71, 13, 10, 26, 10, 0, 0, 0, 13, 73, 72, 68, 82 });
FilesHeader.Add("pdf", new byte[] { 37, 80, 68, 70, 45, 49, 46, 53 });
FilesHeader.Add("docx", new object[] { new byte[] { 80, 75, 3, 4, 20, 0, 6, 0, 8, 0, 0, 0, 33 }, new Regex(@"word/_rels/document\.xml\.rels", RegexOptions.IgnoreCase) });
FilesHeader.Add("xlsx", new object[] { new byte[] { 80, 75, 3, 4, 20, 0, 6, 0, 8, 0, 0, 0, 33 }, new Regex(@"xl/_rels/workbook\.xml\.rels", RegexOptions.IgnoreCase) });
FilesHeader.Add("pptx", new object[] { new byte[] { 80, 75, 3, 4, 20, 0, 6, 0, 8, 0, 0, 0, 33 }, new Regex(@"ppt/_rels/presentation\.xml\.rels", RegexOptions.IgnoreCase) });
FilesHeader.Add("doc", new object[] { new byte[] { 208, 207, 17, 224, 161, 177, 26, 225 }, new Regex(@"microsoft( office)? word(?![\s\S]*?microsoft)", RegexOptions.IgnoreCase) });
FilesHeader.Add("xls", new object[] { new byte[] { 208, 207, 17, 224, 161, 177, 26, 225 }, new Regex(@"microsoft( office)? excel(?![\s\S]*?microsoft)", RegexOptions.IgnoreCase) });
FilesHeader.Add("ppt", new object[] { new byte[] { 208, 207, 17, 224, 161, 177, 26, 225 }, new Regex(@"c.u.r.r.e.n.t. .u.s.e.r(?![\s\S]*?[a-z])", RegexOptions.IgnoreCase) });
FilesHeader.Add("avi", new byte[] { 65, 86, 73, 32 });
FilesHeader.Add("mpg", new byte[] { 0, 0, 1, 0xBA });
FilesHeader.Add("mpeg", new byte[] { 0, 0, 1, 0xB3 });
FilesHeader.Add("rar", new byte[] { 82, 97, 114, 33, 26, 7 });
FilesHeader.Add("zip", new byte[] { 80, 75, 3, 4 });
}
private static string DateTimeStamp()
{
return DateTime.Now.ToString("yyyyMMddHHmmss") + ra.Next(0, 99999).ToString("00000");
}
private static string FileType(Stream str)
{
string FileExt = string.Empty;
foreach (string ext in FilesHeader.Keys)
{
byte[] header = FilesHeader[ext].GetType() == (new byte[] { }).GetType() ? (byte[])FilesHeader[ext] : (byte[])(((object[])FilesHeader[ext])[0]);
byte[] test = new byte[header.Length];
str.Position = 0;
str.Read(test, 0, test.Length);
bool same = true;
for (int i = 0; i < test.Length; i++)
{
if (test[i] != header[i])
{
same = false;
break;
}
}
if (FilesHeader[ext].GetType() != (new byte[] { }).GetType() && same)
{
object[] obj = (object[])FilesHeader[ext];
bool exists = false;
if (obj[1].GetType().ToString() == "System.Int32")
{
for (int ii = 2; ii < obj.Length; ii++)
{
if (str.Length >= (int)obj[1])
{
str.Position = str.Length - (int)obj[1];
byte[] more = (byte[])obj[ii];
byte[] testmore = new byte[more.Length];
str.Read(testmore, 0, testmore.Length);
if (Encoding.GetEncoding(936).GetString(more) == Encoding.GetEncoding(936).GetString(testmore))
{
exists = true;
break;
}
}
}
}
else if (obj[1].GetType().ToString() == "System.Text.RegularExpressions.Regex")
{
Regex re = (Regex)obj[1];
str.Position = 0;
byte[] buffer = new byte[(int)str.Length];
str.Read(buffer, 0, buffer.Length);
string txt = Encoding.ASCII.GetString(buffer);
if (re.IsMatch(txt))
{
exists = true;
}
}
if (!exists)
{
same = false;
}
}
if (same)
{
FileExt = ext;
break;
}
}
if (string.IsNullOrEmpty(FileExt))
{
#region 测试是否为纯文本
Encoding[] chkList = new Encoding[] { Encoding.ASCII, Encoding.UTF8, Encoding.GetEncoding(936) };
for (int i = 0; i < chkList.Length; i++)
{
str.Position = 0;
string str_test = new StreamReader(str, chkList[i]).ReadToEnd();
if (Regex.IsMatch(str_test, @"^[^\u0000-\u0008\u000B-\u000C\u000E-\u001F]*$"))
{
FileExt = "txt";
break;
}
}
#endregion
}
return FileExt;
}
private static void CreateFolder(string path)
{
string t_path = HttpContext.Current.Server.MapPath(path);
if (!Directory.Exists(t_path))
{
Directory.CreateDirectory(t_path);
}
}
private static string CreateFileName(string name, string ext)
{
string filename = "/Upload/" + DateTime.Now.ToString("yyyy/MM/dd") + "/" + ext + "/" + (autonamed ? DateTimeStamp() + "." + ext : name);
if (File.Exists(HttpContext.Current.Server.MapPath(filename)))
{
return CreateFileName(name, ext);
}
else
{
return filename;
}
}
private static string SaveAs(HttpPostedFile file, string Ext)
{
string filename = CreateFileName(file.FileName, Ext);
CreateFolder(Regex.Match(filename, @"^[\s\S]*?(?=[^\\/]+$)").Value);
if (Regex.IsMatch(Ext, @"^(jpg|gif|png|bmp)$"))
{
try
{
Image pic = Image.FromStream(file.InputStream);
}
catch (Exception ex)
{
err = ex.Message + "试图按照图片格式解析时异常。";
return string.Empty;
}
}
if (addmark && Regex.IsMatch(Ext, @"^(jpg|gif|png|bmp)$"))
{
Image img = Image.FromFile(HttpContext.Current.Server.MapPath("/logo.png"));
Image pic = Image.FromStream(file.InputStream);
if (pic.Width > img.Width + 10 && pic.Height > img.Height + 10)
{
Graphics g = Graphics.FromImage(pic);
g.DrawImage(img, pic.Width - img.Width - 5, pic.Height - img.Height - 5);
}
pic.Save(HttpContext.Current.Server.MapPath(filename));
}
else
{
file.SaveAs(HttpContext.Current.Server.MapPath(filename));
}
return Regex.Match(HttpContext.Current.Request.Url.ToString(), @"^[\s\S]*?(?=(?<!/)/(?!/))").Value + filename;
}
private static void SaveInvalid(HttpPostedFile file)
{
}
public static void Clear()
{
script = string.Empty;
}
public static void Save(HttpPostedFile file)
{
err = string.Empty;
if (file.ContentLength == 0)
{
if (file.FileName.Length > 0)
{
script += (script.Length > 0 ? "," : "") + "{filename:'" + file.FileName + "',upload:false,length:0,error:'文件大小为零字节。'}";
}
}
else
{
string ext = FileType(file.InputStream);
byte[] header = new byte[20];
file.InputStream.Position = 0;
file.InputStream.Read(header, 0, 20);
string headString = string.Empty;
for (int i = 0; i < header.Length; i++)
{
headString += (i > 0 ? "," : "") + header[i].ToString();
}
if (string.IsNullOrEmpty(ext))
{
SaveInvalid(file);
script += (script.Length > 0 ? "," : "") + "{filename:'" + file.FileName + "',upload:false,length:" + file.ContentLength + ",error:'不支持的文件类型。',header:['" + headString + "']}";
}
else
{
if (ext == "txt")
{
bool valid = false;
string fileExt = Regex.Match(file.FileName, @"(?<=\.)[a-z]+$", RegexOptions.IgnoreCase).Value.ToLower();
for (int i = 0; i < txtType.Length; i++)
{
if (fileExt == txtType[i])
{
ext = txtType[i];
valid = true;
break;
}
}
if (!valid)
{
script += (script.Length > 0 ? "," : "") + "{filename:'" + file.FileName + "',upload:false,length:" + file.ContentLength + ",error:'不被支持的文本文档格式。',type:'" + fileExt + "'}";
return;
}
}
string filename = SaveAs(file, ext);
if (!string.IsNullOrEmpty(filename))
{
script += (script.Length > 0 ? "," : "") + "{filename:'" + file.FileName + "',upload:true,length:" + file.ContentLength + ",target:'" + filename + "',type:'" + ext + "'}";
}
else
{
script += (script.Length > 0 ? "," : "") + "{filename:'" + file.FileName + "',upload:false,length:" + file.ContentLength + ",error:'" + err + "',type:'" + ext + "'}";
}
}
}
}
}
请记住转载地址 http://blog.csdn.net/superwfei