views:

636

answers:

6

I have a FileUpload control (FileUpload1) on my web form, as well as a "Sumbit" button, a label, and a hidden field that contains a UserID. I have the following code in the button's click event:

string path = Server.MapPath("~/userfiles/");

if (FileUpload.HasFile)
{
    try 
    {
        FileUpload1.SaveAs(path + UserID.Value + "/image.jpg");
    }
    catch 
    {
        Label1.Text = "* unable to upload file";
        Label1.Visible = true; 
    }
}

It works great if I upload an actual file. However, if I type a non-existent filename (for example, "c:\a.jpg", which does not exist on my computer) into the FileUpload's textbox, and click the Sumbit button, HasFile still returns true. Furthermore, SaveAs() does not throw any exceptions, and it is a void function that returns no value indicating success or failure. How do I tell whether a file was actually uploaded?

+7  A: 

Just check to see if it exists.

if(File.Exists(myFile)){
  //it was uploaded.
}
jvenema
+2  A: 

You could check if the file exists using File.Exists before calling SaveAs.

Rob Windsor
+3  A: 

You could check FileUpload.PostedFile.ContentLength property

Alex Reitbort
A: 

Hmmm....

Not sure I understand. First, in your code, FileUpload.HasFile won't compile. If should be FileUpload1.HasFile.

When I correct this, and run your code, this line returns false if the file does not exist...

You can check if file exists after uploading using File.Exists(path); The file object is part of System.IO.

A: 

This is not about your actual question, but you should validate any user input, especially if you want users to upload files to a virtual folder on your webserver. You should at least check whether the content type of the file is the one you expect, or - even better, filter (resize) the image using the classes available in the .NET framework.

If you don't do so users may share arbitrary content via your site or place malicious files (e.g. images containing script which might get executed by certain web browsers) on your server.

With additional validation you will also be able to validate if there has actually been content sent.

AND: A really severe vulnerability opens up when you build the save path by concatenating input from a form field (I assume UserID.Value is the POST parameter you mention?). This allows users to decide where to store the content on your server, and, even worse, be able to overwrite existing files!!!

0xA3
A: 

Hi I have the same issue. But lil different one. When i type some thing instead of file name say i typed "absfsdff" then clicked the submit button then i found that click event is not firing. the page remains same no postback happens. how to handle this. Thanks

Rupesh Tiwari