Checking file size before an file is posted RRS feed

  • Question

  • User-139037907 posted
    I need to determine a file's size before it becomes a PostedFile, and, if it is over 2MB, redirect the user to an error page. If it's under 2MB, then upload the file to the server. I looked at the thread for "HttpHandler or HttpModule for file upload, large files, progress indicator?", and it looked like far more than what I needed (and was WAY above my head), so I was wondering has anyone come up with a solution just for this? TIA. J
    Wednesday, February 25, 2004 11:52 AM

All replies

  • User1220193301 posted
    I think you would still need a HttpModule to accomplish this. The idea is similar to the one you read in that other post ("HttpHandler or HttpModule for file upload, large files, progress indicator?"). Of course, you don't need to worry about buffering the file and setting up a progress indicator. Here is what you need to do inside the HttpModule: public void Init(HttpApplication context) { context.BeginRequest += new EventHandler(this.OnBeginRequest); } public void OnBeginRequest(object sender, EventArgs args) { // Get the application that generated the request HttpApplication app = (HttpApplication)sender; // Get the internal request worker BindingFlags bindingFlags = BindingFlags.Instance | BindingFlags.NonPublic; HttpWorkerRequest req = (HttpWorkerRequest)app.Context.GetType().GetProperty("WorkerRequest", bindingFlags).GetValue(app.Context, null); // Get the total number of bytes in the request // Note this includes both the file and other HTTP headers! contentLength = System.Convert.ToInt32(req.GetKnownRequestHeader(HttpWorkerRequest.HeaderContentLength)); if (2048 < contentLength) { throw new System.Exception("File is too large"); } else { // don't do anything and the request should flow // through the rest of the HTTP pipeline to // end up as PostedFile object. } } I haven't tested this code out, but this should give you an idea ;). Again keep in mind that the "2048" there is for the total bytes in the request which includes the file data and other HTTP headers, boundaries, etc...
    Thursday, February 26, 2004 4:39 PM