Friday, December 31, 2010

Showing the size of an image after it has been uploaded using AJAX AsyncFileUpload file control

On Wednesday, I was working on some code that will accept an upload of an image file and after the image upload is complete, the page will display the dimensions of the image that was uploaded.

I had problems getting my original code to work though. I getting this error "The process cannot access the file because it is being used by another process". Below is my original code.

AsyncFileUpload upload = (AsyncFileUpload)sender;
   String filename = System.IO.Path.GetFileName(upload.FileName);
   String filePathName = Server.MapPath("images/") + filename;
   upload.SaveAs(filePathName);

   System.Drawing.Image image = System.Drawing.Image.FromFile(filePathName);
  
   if (image != null){            
     String msg = "Uploaded " + filename + " of size " + 
                  image.Width + "x" + image.Height;
     Label1.Text = msg;
}

After numerous trials and errors and after alot of Googling, I finally figured out that the problem was due to a GDI+ bug that locks up the Image handle.

The thread above suggested some workarounds for the problem, but I didn't try them, instead, I thought since I was encountering the lock problem because one process was trying to save the File, while another process was trying to read the file, maybe I can try to read the file by creating an Image from Stream instead of disk instead.

Sure enough, after I managed to find out how to create an Image object from Stream and modified my code accordingly, the thing worked! ^_^

Anyway, the modified code only needed one change, that is to change the line of code as highlighted below:

protected void AsyncFileUpload1_UploadedComplete(object sender, AsyncFileUploadEventArgs e)
    {
        AsyncFileUpload upload = (AsyncFileUpload)sender;
        String filename = System.IO.Path.GetFileName(upload.FileName);

        String filePathName = Server.MapPath("images/") + filename;
        upload.SaveAs(filePathName);


        System.Drawing.Image image = System.Drawing.Image.FromStream(upload.FileContent);

        if (image != null)
        {            
            String msg = "Uploaded " + filename 
                         + " of size " + image.Width + "x" + image.Height;
            Label1.Text = msg;
        }
    }

No comments: