Erick
Erick

Reputation: 853

Asp.Net advanced file uploading

When using a standard <input type="file" /> on an mvc3 site, you can receive the file in your action method by creating an input parameter of type HttpPostedFile and setting the form to enctype="multipart/form-data"

One of the problems of this approach is that the request does not complete and is not handed off to your action method until the entire contents of the file have been uploaded.

I would like to do some things to that file as it is being uploaded to the server. Basically i want to asynchronously receive the data as it comes in and then programmatically handle the data byte by byte.

To accomplish the above I imagine you will need to handle this part of the request in an HttpModule or custom HttpHandler perhaps. I am familiar with how those things work, but I am not familiar with the method of receiving the file upload data asynchronously as it comes in.

I know this is possible because I have worked with 3rd party components in the past that do this (normally so they can report upload progress, or cache the data to disk to avoid iis/asp.net memory limitations). Unfortunately all the components I have used are closed source so I can't peek inside and see what they are doing.

I am not looking for code, but can someone get me pointed in the right direction here?

Upvotes: 6

Views: 899

Answers (1)

Chuck Savage
Chuck Savage

Reputation: 11955

Using a WCF service you can send file streams to and from your service.

Here is the service side receive code I use:

int chunkSize = 2048;
byte[] buffer = new byte[chunkSize];

using (System.IO.FileStream writeStream =
    new System.IO.FileStream(file.FullName, System.IO.FileMode.CreateNew, System.IO.FileAccess.Write))
{
    do
    {
        // read bytes from input stream
        int bytesRead = request.FileByteStream.Read(buffer, 0, chunkSize);
        if (bytesRead == 0) break;

        // write bytes to output stream
        writeStream.Write(buffer, 0, bytesRead);
    } while (true);

    writeStream.Close();
}

If that looks like what you want, check out the CodeProject File Transfer Progress. It goes into a lot of detail that my code is loosely based on.

Upvotes: 1

Related Questions