大文件上传

来源:互联网 发布:seo关键词优化方案 编辑:程序博客网 时间:2024/06/07 06:35
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="File.aspx.cs" Inherits="BigFile.File" %>


<!DOCTYPE html>


<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
    <title></title>
    <script src="jquery-1.4.1.min.js"></script>
</head>
<body>
    <form id="form1" runat="server" enctype="multipart/form-data" method="post">
        <div>
            <input id="firstFile" type="file" name="firstFile" runat="server" /><br />
            <asp:Button ID="Button1" runat="server" OnClick="Button1_Click" Text="上传" /><br />
            <asp:Label ID="Label1" runat="server"></asp:Label>
        </div>
    </form>
</body>

</html>


HttpUploadModule.cs

using System;
using System.Collections;
using System.Collections.Specialized;
using System.Globalization;
using System.IO;
using System.Text;
using System.Web;
using System.Reflection;


namespace BigFile
{
    public class HttpUploadModule : IHttpModule
    {
        public HttpUploadModule()
        {


        }


        public void Init(HttpApplication application)
        {
            //订阅事件
            application.BeginRequest += new EventHandler(this.Application_BeginRequest);
        }


        public void Dispose()
        {
        }


        private void Application_BeginRequest(Object sender, EventArgs e)
        {
            HttpApplication app = sender as HttpApplication;
            HttpWorkerRequest request = GetWorkerRequest(app.Context);
            Encoding encoding = app.Context.Request.ContentEncoding;


            int bytesRead = 0; // 已读数据大小
            int read;           // 当前读取的块的大小
            int count = 8192;   // 分块大小
            byte[] buffer;      // 保存所有上传的数据


            if (request != null)
            {
                // 返回 HTTP 请求正文已被读取的部分。
                byte[] tempBuff = request.GetPreloadedEntityBody(); //要上传的文件


                // 如果是附件上传
                if (tempBuff != null && IsUploadRequest(app.Request))    //判断是不是附件上传
                {
                    // 获取上传大小
                    // 
                    long length = long.Parse(request.GetKnownRequestHeader(HttpWorkerRequest.HeaderContentLength));


                    buffer = new byte[length];
                    count = tempBuff.Length; // 分块大小


                    // 将已上传数据复制过去
                    //
                    Buffer.BlockCopy(tempBuff, //源数据
                        0,                      //从0开始读
                        buffer,                 //目标容器
                        bytesRead,              //指定存储的开始位置
                        count);                 //要复制的字节数。 




                    // 开始记录已上传大小
                    bytesRead = tempBuff.Length;


                    // 循环分块读取,直到所有数据读取结束
                    while (request.IsClientConnected() && !request.IsEntireEntityBodyIsPreloaded() && bytesRead < length)
                    {
                        // 如果最后一块大小小于分块大小,则重新分块
                        if (bytesRead + count > length)
                        {
                            count = (int)(length - bytesRead);
                            tempBuff = new byte[count];
                        }


                        // 分块读取
                        read = request.ReadEntityBody(tempBuff, count);


                        // 复制已读数据块
                        Buffer.BlockCopy(tempBuff, 0, buffer, bytesRead, read);


                        // 记录已上传大小
                        bytesRead += read;


                    }
                    if (request.IsClientConnected() && !request.IsEntireEntityBodyIsPreloaded())
                    {
                        // 传入已上传完的数据
                        InjectTextParts(request, buffer);
                    }
                }
            }
        }




        HttpWorkerRequest GetWorkerRequest(HttpContext context)
        {


            IServiceProvider provider = (IServiceProvider)HttpContext.Current;
            return (HttpWorkerRequest)provider.GetService(typeof(HttpWorkerRequest));
        }


        /// <summary>
        /// 传入已上传完的数据
        /// </summary>
        /// <param ></param>
        /// <param ></param>
        void InjectTextParts(HttpWorkerRequest request, byte[] textParts)
        {
            BindingFlags bindingFlags = BindingFlags.Instance | BindingFlags.NonPublic;


            Type type = request.GetType();


            while ((type != null) && (type.FullName != "System.Web.Hosting.ISAPIWorkerRequest"))
            {
                type = type.BaseType;
            }


            if (type != null)
            {
                type.GetField("_contentAvailLength", bindingFlags).SetValue(request, textParts.Length);
                type.GetField("_contentTotalLength", bindingFlags).SetValue(request, textParts.Length);
                type.GetField("_preloadedContent", bindingFlags).SetValue(request, textParts);
                type.GetField("_preloadedContentRead", bindingFlags).SetValue(request, true);
            }
        }


        private static bool StringStartsWithAnotherIgnoreCase(string s1, string s2)
        {
            return (string.Compare(s1, 0, s2, 0, s2.Length, true, CultureInfo.InvariantCulture) == 0);
        }


        /// <summary>
        /// 是否为附件上传
        /// 判断的根据是ContentType中有无multipart/form-data
        /// </summary>
        /// <param ></param>
        /// <returns></returns>
        bool IsUploadRequest(HttpRequest request)
        {
            return StringStartsWithAnotherIgnoreCase(request.ContentType, "multipart/form-data");
        }
    }
}



<?xml version="1.0" encoding="UTF-8"?>
<configuration>
  <appSettings>
    <add key="ConStringEncrypt" value="false" />
    <!--短信签名 公司名称-->
    <add key="ImageServerWebPath" value="http://10.10.20.183:84/File/"  />
    <!--图片服务器的本地路径-->
    <add key="ImageServerLocalPath" value="E:\主干\WebSites\Manage\File\" />


  </appSettings>
  <connectionStrings />
  <system.web>
    <httpRuntime maxRequestLength="2097151"  executionTimeout="120"/>
    <compilation debug="true" />
    <!--
            通过 <authentication> 节可以配置
            安全身份验证模式,ASP.NET 
            使用该模式来识别来访用户身份。 
        -->
    <authentication mode="Windows" />
    <customErrors mode="RemoteOnly" defaultRedirect="GenericErrorPage.htm">
      <error statusCode="403" redirect="NoAccess.htm" />
      <error statusCode="404" redirect="FileNotFound.htm" />
    </customErrors>


    <httpModules>
      <add name="HttpUploadModule"
         type="BigFile.HttpUploadModule, BigFile" />
    </httpModules>
    


    <httpHandlers>
      <add path="*.myh" verb="GET" type="MyApp.MyHandler" />
    </httpHandlers>


    <pages />
    <sessionState timeout="6000" />
  </system.web>
  <system.webServer>
    <security>
      <requestFiltering >
        <requestLimits maxAllowedContentLength="2147483647" ></requestLimits>
      </requestFiltering>
    </security>
    <modules>
      <add name="HttpUploadModule" type="BigFile.HttpUploadModule, BigFile"/>
    </modules>
    <handlers>
      <add name="MyHandler" path="*.myh" verb="GET" type="MyApp.MyHandler" preCondition="integratedMode" />
    </handlers>
    <validation validateIntegratedModeConfiguration="false" />
    
    <directoryBrowse enabled="true" />
    <defaultDocument>
      <files>
        <add value="Login.aspx" />
      </files>
    </defaultDocument>
    <staticContent>
      <mimeMap fileExtension=".cfg" mimeType="application/octet-stream" />
    </staticContent>
  </system.webServer>
</configuration>

1 0
原创粉丝点击