I have a file upload on my .NET website. I used the FileUpload .NET control for the upload, and set the target of the form to a hidden iframe. I use client-side script to submit the form, then display a progress bar on the page, which does an AJAX request to an ashx file on the same server and updates the progress bar every second.
Here’s the part of the code for when the file is uploading –
string fileString = StringGenerator.GenerateString(8);
System.IO.Stream fileStream = System.IO.File.Create(fileRoot+ fileString + ".mp3");
System.IO.Stream inputStream = fileUpload.PostedFile.InputStream;
byte[] buffer = new byte[256];
int read;
if(StaticProgress.Progress.ContainsKey(trackId)) StaticProgress.Progress[trackId] = 0d;
else StaticProgress.Progress.Add(trackId, 0d);
int totalRead = 0;
long length = inputStream.Length;
while ((read = inputStream.Read(buffer, 0, buffer.Length)) > 0)
{
totalRead += read;
fileStream.Write(buffer, 0, read);
StaticProgress.Progress[trackId] = (double)totalRead / (double)length;
}
StaticProgress.Progress is a property which returns a static Dictionary.
Here is the code in the ashx file that gets the progress of the
context.Response.ContentType = "text/javascript";
int id;
if(!int.TryParse(context.Request.QueryString["id"], out id) || !StaticProgress.Progress.ContainsKey(id))
context.Response.Write("{\"error\":\"ID not found\"}");
else
context.Response.Write("{\"id\":\"" + id + "\",\"decimal\":" + StaticProgress.Progress[id] + "}");
Here I always “ID not found” while the file is uploading, but when the file has finished uploading, I get a successful – decimal : 1.
I’ve tried using session variables before this and got the same result. I’ve tried using a public static (thread safe?) Dictionary, but I get the same result. Has anyone came across anything like this before? Does the code not execute until the client request has been fully received?
The standard file upload control provides no progress abilities – it does not receive the file until the file has been fully received by the server. By the time you open the stream on the .PostedFile, the file has been completely uploaded.
There are a number of better solutions to uploading discussed here.