ASP.NET File Upload differences between Firefox and IE

Written on

When using an ASP.NET File Upload control (or the HTML equivalent) it's worth remembering that when you come to use the FileName property in your code, it annoyingly has different values depending on what browser you are using.

If you have one of these on your page...

<asp:FileUpload id="FileUpload1" runat="server" /> 

... or the HTML version...

<input id="FileUpload2" runat="server" type="file" />

... when you come to get the name of the user-selected file in your code (which for example was a file picture.jpg in C:\Pics\), you will get the following results depending on the users browser:

Control: FileUpload1 FileUpload1 FileUpload2 FileUpload2
Property: FileName PostedFile.FileName Value PostedFile.FileName
Firefox 2 picture.jpg picture.jpg picture.jpg picture.jpg
Firefox 3 picture.jpg picture.jpg picture.jpg picture.jpg
IE7 picture.jpg C:\Pics\picture.jpg C:\Pics\picture.jpg C:\Pics\picture.jpg
Opera 9 picture.jpg picture.jpg picture.jpg picture.jpg
Safari 3 picture.jpg picture.jpg picture.jpg picture.jpg

As you can see, it is Internet Explorer that is the odd one out. What this means is that you can't rely on using the FileName property without first checking the value and trimming out the unwanted file path. For example, to get picture.jpg no matter what browser is used, you'll have to do something like this:

string file = FileUpload2.PostedFile.FileName;
int slash = file.LastIndexOf("\\");
if (slash > 0) file = file.Substring(slash, file.Length - 1);

Don't let this catch you out.


Comments

I´m trying to read a file, without upload it to the server, and for that, I need the full path. Do you have an example of code to always get c:\pics\picture.jpg? Thanks, L

Luis Lau

Hi Luis: If you want the path information (i.e. the "c:\pics\" part) I'm afraid you can't get it by using the FileUpload control (apart from if the client is using IE, like my post describes. But of course you can't rely on that). Some of the posts here explain why the server can't access the file structure of the posted file: http://forums.asp.net/p/1077850/1587461.aspx In short, your program could be buggy if you're relying on the clients file structure anyway: it might change without you knowing and then break your code. Also, it's not relevant once the file is posted to the server. It's the file that is the relevant thing; not the folder structure where the file was located. The above post has some suggestions for a workaround. The full path of the file could be stored somewhere else (in a hidden field) - although I haven't tried this method myself. You might want to take a look at this link too: http://forums.asp.net/p/1170634/1959688.aspx

Alex

You could also use Path.GetFileName() (System.IO). string file = Path.GetFileName(FileUpload2.PostedFile.FileName); Personally I prefer using the builtin framework methods as often as possible.

Thomas Mandelid