一般处理程序上传文件(html表单上传、aspx页面上传)

html 表单上传文件

       一般处理程序由于没有 apsx 页面的整个模型和控件的创建周期,而比较有效率。这里写一个用 html 表单进行文件上传的示例。

       1. 表单元素选用 <input type="file"> 控件。

       2. form 表单需要设置 enctype="multipart/form-data" 属性,请求报文体中数据格式也由键值对更改为数据头和数具体,并有随机边界符分割。

       3. 服务器端接收文件使用 Request.Files 属性。

       4. 使用 HttpPostedFile 的 SaveAs 方法保存文件(需转换成网站物理路径)。

 

 

<body>
    <form action="UploadFile.ashx" method="post" enctype="multipart/form-data">
    <input type="file" name="fileUpload" />
    <input type="submit" value="上传文件" />
    </form>
</body>
public void ProcessRequest(HttpContext context)
{
    context.Response.ContentType = "text/html";
    HttpServerUtility server = context.Server;
    HttpRequest request = context.Request;
    HttpResponse response = context.Response;
 
    HttpPostedFile file = context.Request.Files[0];
    if (file.ContentLength > 0)
    {
        string extName = Path.GetExtension(file.FileName);
        string fileName = Guid.NewGuid().ToString();
        string fullName = fileName + extName;
 
        string imageFilter = ".jpg|.png|.gif|.ico";// 随便模拟几个图片类型
        if (imageFilter.Contains(extName.ToLower()))
        {
            string phyFilePath = server.MapPath("~/Upload/Image/") + fullName;
            file.SaveAs(phyFilePath);
            response.Write("上传成功!文件名:" + fullName + "<br />");
            response.Write(string.Format("<img src='Upload/Image/{0}'/>", fullName));
        }
    }
}

 

 

html 表单批量上传文件

       如果要实现批量上传,需要重构一般处理程序中文件保存的逻辑以代码重用,或者在上述代码中增加循环 Files 集合:

public void ProcessRequest(HttpContext context)
{
    context.Response.ContentType = "text/html";
    HttpServerUtility server = context.Server;
    HttpRequest request = context.Request;
    HttpResponse response = context.Response;
 
    HttpFileCollection files = context.Request.Files;
 
    for (int i = 0; i < files.Count; i++)
    {
        if (files[i].ContentLength > 0)
        {
            string extName = Path.GetExtension(files[i].FileName);
            string fileName = Guid.NewGuid().ToString();
            string fullName = fileName + extName;
 
            string imageFilter = ".jpg|.png|.gif|.ico";// 随便模拟几个图片类型
            if (imageFilter.Contains(extName.ToLower()))
            {
                string phyFilePath = server.MapPath("~/Upload/Image/") + fullName;
                files[i].SaveAs(phyFilePath);
                response.Write("上传成功!文件名:" + fullName + "<br />");
                response.Write(string.Format("<img src='Upload/Image/{0}'/><br />", fullName));
            }
        }
    }
}

 

 

如何判断上传文件类型是指定类型?

       怎么确定上传文件的类型是指定类型,而不是仅仅修改了后缀名的欺骗文件?

       对于一些精确控制的需求,可以通过读取文件头的字节来确定文件的真实类型。这些文件头的类型就非常之多了,下面仅记录一些较为常用的类型(网上可搜索):

FFD8FFFE00, .JPEG;.JPE;.JPG, "JPG Graphic File"

FFD8FFE000, .JPEG;.JPE;.JPG, "JPG Graphic File"

474946383961, .gif, "GIF 89A"

474946383761, .gif, "GIF 87A"

424D, .bmp, "Windows Bitmap"

4D5A, .exe;.com;.386;.ax;.acm;.sys;.dll;.drv;.flt;.fon;.ocx;.scr;.lrc;.vxd;.cpl;.x32, "Executable File"

504B0304, .zip, "Zip Compressed"

3A42617365, .cnt, ""

D0CF11E0A1B11AE1, .doc;.xls;.xlt;.ppt;.apr, "MS Compound Document v1 or Lotus Approach APR file"

0100000058000000, .emf, ""

03000000C466C456, .evt, ""

3F5F0300, .gid;.hlp;.lhp, "Windows Help File"

1F8B08, .gz, "GZ Compressed File"

28546869732066696C65, .hqx, ""

0000010000, .ico, "Icon File"

4C000000011402, .lnk, "Windows Link File"

25504446, .pdf, "Adobe PDF File"

5245474544495434, .reg, ""

7B5C727466, .rtf, "Rich Text Format File"

lh, .lzh, "Lz compression file"

MThd, .mid, ""

0A050108, .pcx, ""

25215053, .eps, "Adobe EPS File"

2112, .ain, "AIN Archive File"

1A02, .arc, "ARC/PKPAK Compressed 1"

1A03, .arc, "ARC/PKPAK Compressed 2"

1A04, .arc, "ARC/PKPAK Compressed 3"

1A08, .arc, "ARC/PKPAK Compressed 4"

1A09, .arc, "ARC/PKPAK Compressed 5"

60EA, .arj, "ARJ Compressed"

41564920, .avi, "Audio Video Interleave (AVI)"

425A68, .bz;.bz2, "Bzip Archive"

49536328, .cab, "Cabinet File"

4C01, .obj, "Compiled Object Module"

303730373037, .tar;.cpio, "CPIO Archive File"

4352555348, .cru;.crush, "CRUSH Archive File"

3ADE68B1, .dcx, "DCX Graphic File"

1F8B, .gz;.tar;.tgz, "Gzip Archive File"

91334846, .hap, "HAP Archive File"

3C68746D6C3E, .htm;.html, "HyperText Markup Language 1"

3C48544D4C3E, .htm;.html, "HyperText Markup Language 2"

3C21444F4354, .htm;.html, "HyperText Markup Language 3"

100, .ico, "ICON File"

5F27A889, .jar, "JAR Archive File"

2D6C68352D, .lha, "LHA Compressed"

20006040600, .wk1;.wks, "Lotus 123 v1 Worksheet"

00001A0007800100, .fm3, "Lotus 123 v3 FMT file"

00001A0000100400, .wk3, "Lotus 123 v3 Worksheet"

20006800200, .fmt, "Lotus 123 v4 FMT file"

00001A0002100400, .wk4, "Lotus 123 v5"

5B7665725D, .ami, "Lotus Ami Pro"

300000041505052, .adx, "Lotus Approach ADX file"

1A0000030000, .nsf;.ntf, "Lotus Notes Database/Template"

4D47582069747064, .ds4, "Micrografix Designer 4"

4D534346, .cab, "Microsoft CAB File Format"

4D546864, .mid, "Midi Audio File"

000001B3, .mpg;.mpeg, "MPEG Movie"

0902060000001000B9045C00, .xls, "MS Excel v2"

0904060000001000F6055C00, .xls, "MS Excel v4"

7FFE340A, .doc, "MS Word"

1234567890FF, .doc, "MS Word 6.0"

31BE000000AB0000, .doc, "MS Word for DOS 6.0"

1A00000300001100, .nsf, "Notes Database"

7E424B00, .psp, "PaintShop Pro Image File"

504B0304, .zip, "PKZIP Compressed"

89504E470D0A, .png, "PNG Image File"

6D646174, .mov, "QuickTime Movie"

6D646174, .qt, "Quicktime Movie File"

52617221, .rar, "RAR Archive File"

2E7261FD, .ra;.ram, "Real Audio File"

EDABEEDB, .rpm, "RPM Archive File"

2E736E64, .au, "SoundMachine Audio File"

53495421, .sit, "Stuffit v1 Archive File"

53747566664974, .sit, "Stuffit v5 Archive File"

1F9D, .z, "TAR Compressed Archive File"

49492A, .tif;.tiff, "TIFF (Intel)"

4D4D2A, .tif;.tiff, "TIFF (Motorola)"

554641, .ufa, "UFA Archive File"

57415645666D74, .wav, "Wave Files"

D7CDC69A, .wmf, "Windows Meta File"

4C000000, .lnk, "Windows Shortcut (Link File)"

504B3030504B0304, .zip, "WINZIP Compressed"

FF575047, .wpg, "WordPerfect Graphics"

FF575043, .wp, "WordPerfect v5 or v6"

3C3F786D6C, .xml, "XML Document"

FFFE3C0052004F004F0054005300540055004200, .xml, "XML Document (ROOTSTUB)"

3C21454E54495459, .dtd, "XML DTD"

 

       另外,还可以通过 HttpPostedFile 对象的 ContentType 属性来得到文件的 MIME 内容类型

 

 

如何上传超大文件?

       ASP.NET 默认的请求长度为 4096,如果头信息中 Content-Length 的请求长度超过默认的值, IIS 将返回一个 403 错误信息。显然,你会直接联想到以下 2 种解决方案:

  1. 修改 web.config 的配置,扩大此 Web 项目请求长度的限制:
<system.web>
    <httpRuntime maxRequestLength="40960" executionTimeout="3600" />
</system.web>

   2. 修改 C:\WINDOWS\Microsoft.NET\Framework\v4.0.30319\Config\machine.config 中的对应节,如上(所有 Web 项目都突破了默认限制)。

 

      在 IIS 7.0 之后,最大上传文件的尺寸好像是 2GB。

posted on 2014-01-18 15:27  SkySoot  阅读(23792)  评论(3编辑  收藏  举报

导航