.net文件上传时实现通过文件头确认文件类型的方法
程序员文章站
2024-02-21 12:20:46
本文实例讲述了.net文件上传时实现通过文件头确认文件类型的方法,其中 script 用来返回给页面的数据,读者还可以根据自身需要对相关部分自行修改。另外,文件头也可以自行...
本文实例讲述了.net文件上传时实现通过文件头确认文件类型的方法,其中 script 用来返回给页面的数据,读者还可以根据自身需要对相关部分自行修改。另外,文件头也可以自行添加定义。
主要代码如下:
appcode/fileupload.cs using system; using system.collections.generic; 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(); public static bool autonamed { get { return autonamed; } set { autonamed = value; } } public static string script { get { return "var upload = [" + script + "];"; } } public static dictionary<string, byte[]> imageheader = new dictionary<string, byte[]>(); public static dictionary<string, object> filesheader = new dictionary<string, object>(); static fileupload() { imageheader.add("gif", new byte[] { 71, 73, 70, 56, 57, 97 }); imageheader.add("bmp", new byte[] { 66, 77 }); imageheader.add("jpg", new byte[] { 255, 216, 255 }); imageheader.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; } } return fileext; } private static string imagetype(stream str) { string fileext = string.empty; foreach (string ext in imageheader.keys) { byte[] header = imageheader[ext]; 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 (same) { fileext = ext; break; } } if (!string.isnullorempty(fileext)) { 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 = string.empty; break; } } } 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); 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) { if (file.contentlength == 0) { if (file.filename.length > 0) { script += (script.length > 0 ? "," : "") + "{filename:'" + file.filename + "',upload:false,length:0,target:null,type:''}"; } } else { if (regex.ismatch(file.contenttype, @"^image/")) { string ext = imagetype(file.inputstream); if (string.isnullorempty(ext)) { saveinvalid(file); script += (script.length > 0 ? "," : "") + "{filename:'" + file.filename + "',upload:false,length:" + file.contentlength + ",target:null,type:''}"; } else { string filename = saveas(file, ext); script += (script.length > 0 ? "," : "") + "{filename:'" + file.filename + "',upload:true,length:" + file.contentlength + ",target:'" + filename + "',type:'" + ext + "'}"; } } else if (regex.ismatch(file.contenttype, @"^text/")) { } else { string ext = filetype(file.inputstream); if (string.isnullorempty(ext)) { saveinvalid(file); script += (script.length > 0 ? "," : "") + "{filename:'" + file.filename + "',upload:false,length:" + file.contentlength + ",target:null,type:'',header:[" + "" + "]}"; } else { string filename = saveas(file, ext); script += (script.length > 0 ? "," : "") + "{filename:'" + file.filename + "',upload:true,length:" + file.contentlength + ",target:'" + filename + "',type:'" + ext + "'}"; } } } } }
调用页面:
using system; using system.web; public partial class _default : system.web.ui.page { protected void page_load(object sender, eventargs e) { httpfilecollection files = request.files; fileupload.clear(); for (int i = 0; i < files.count; i++) { fileupload.save(files[i]); } response.write(fileupload.script); } }
功能至此完成,读者还可以根据自身需要进一步作出修改与完善。
上一篇: 三角形最大周长-LeetCode签到
下一篇: java打印当前方法名示例分享