asp.net use HttpWorkerRequest to upload large files

Source: Internet
Author: User

Front Page

<form id= "Form1" runat= "Server" enctype= "Multipart/form-data" method= "POST" >
<div>
<input id= "Firstfile" type= "file" Name= "Firstfile" runat= "Server" ><br/>
&nbsp;<asp:button id= "Button1" runat= "Server" onclick= "button1_click" text= "Upload"/><br/>
<asp:label id= "Label1" runat= "Server" ></asp:Label></div>
</form>

Background page

protected void Page_Load (object sender, EventArgs e)
{

}

protected void Button1_Click (object sender, EventArgs e)
{
The location to save
String Strdespath = "d:\\";
String strFileName = This.firstFile.PostedFile.FileName;
strFileName =strdespath + strFileName;
//
This.firstFile.PostedFile.SaveAs (strFileName);
This. Label1.Text = "File saved to:" + strFileName;
}

Configuration file

<add name= "Httpuploadmodule" type= "Httpmodelapp.httpuploadmodule, Httpmodelapp"/>

Class

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 Httpmodelapp
{
Implement IHttpModule interface
public class Httpuploadmodule:ihttpmodule
{
Public Httpuploadmodule ()
{

}

public void Init (HttpApplication application)
{
Subscribe to Events
Application. BeginRequest + = new EventHandler (this. Application_BeginRequest);
}

public void Dispose ()
{
}

        private void Application_BeginRequest (Object sender, EventArgs e)
& nbsp;       {
             HttpApplication app = sender as HttpApplication;
            HttpWorkerRequest request = Getworkerrequest (app. context);
            Encoding Encoding = App. Context.Request.ContentEncoding;

int bytesread = 0; Read Data size
int read; The size of the block currently being read
int count = 8192; Chunking size
byte[] buffer; Save all uploaded data

if (Request!= null)
{
Returns the portion of the HTTP request body that has been read.
byte[] Tempbuff = Request. Getpreloadedentitybody (); Files to upload

If the attachment is uploaded
if (tempbuff!= null && isuploadrequest (APP). Request)//To determine if attachment upload
{
Get upload Size
//
Long length = long. Parse (Request. Getknownrequestheader (httpworkerrequest.headercontentlength));

Buffer = new Byte[length];
Count = Tempbuff.length; Chunking size

Copy uploaded data to the past
//
Buffer.blockcopy (Tempbuff,//source data
0,//starting from 0 read
Buffer,//target container
Bytesread,//Specify the start location of the store
count); The number of bytes to replicate.


Start recording uploaded size
Bytesread = Tempbuff.length;

Loop-block read until all data reads end
while (request. IsClientConnected () &&!request. isentireentitybodyispreloaded () && bytesread < length)
{
If the last piece size is less than the block size, the block is split again
if (Bytesread + count > Length)
{
Count = (int) (length-bytesread);
Tempbuff = new Byte[count];
}

Chunk Read
Read = Request. Readentitybody (Tempbuff, Count);

Copy a read block of data
Buffer.blockcopy (tempbuff, 0, buffer, bytesread, read);

Record already uploaded size
Bytesread + = read;

}
if (request). IsClientConnected () &&!request. Isentireentitybodyispreloaded ())
{
Passing in data that has been uploaded
Injecttextparts (request, buffer);
}
}
}
}


HttpWorkerRequest Getworkerrequest (HttpContext context)
{

IServiceProvider Provider = (IServiceProvider) httpcontext.current;
Return (HttpWorkerRequest) provider. GetService (typeof (HttpWorkerRequest));
}

<summary>
Passing in data that has been uploaded
</summary>
<param name= "Request" ></param>
<param name= "Textparts" ></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>
Whether to upload an attachment
The basis of judgment is whether there are any multipart/form-data in contenttype
</summary>
<param name= "Request" ></param>
<returns></returns>
BOOL Isuploadrequest (HttpRequest request)
{
return Stringstartswithanotherignorecase (Request. ContentType, "Multipart/form-data");
}
}
}

Note: You need to add a reference HttpModelApp.dll

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.