问题
When I upload a file to a site using the ASP:File control the FileName property is different in IE and Firefox. In Firefox, it just provides the name of the file, but IE provides the full path to the file.
I have worked around this by adding the code:
Dim FileName As String = file.FileName
If FileName.LastIndexOf("\") > 0 Then
FileName = FileName.Substring(FileName.LastIndexOf("\") + 1)
End If
But I'm not sure why that would be different between the different browsers. Does anyone know the reason for this?
Thanks.
回答1:
This is a security/privacy concern, firefox/mozilla is doing it right and you will not get a way to get the full path without an add-in, applet, silverlight, flash or some other mechanism.
Here is more info on Mozilla's stance:
https://developer.mozilla.org/en/Updating_web_applications_for_Firefox_3
See the section on Security Changes->File upload fields
I hope IE will follow suit so we have a consistent and secure environment.
回答2:
A simple workaround for this tested in IE and Chrome
new FileInfo(myHttpPostedFileBase.FileName).Name
This will ensure you always get just the file name even if the path is included.
回答3:
In IE8, this behavior has changed and it will ONLY pass the file name, not the full path. ;-)
Details and link to the IE Blog post discussing the change in IE8: http://blogs.msdn.com/b/webtopics/archive/2009/07/27/uploading-a-file-using-fileupload-control-fails-in-ie8.aspx
Serverside apps looking to parse out the filename should check for, but not expect there to be backslashes in the filename.
IE8 user setting override: http://blogs.msdn.com/blogfiles/webtopics/WindowsLiveWriter/UploadingafileusingFileUploadcontrolfail_167/clip_image002_2.jpg
回答4:
You also can use Path.GetFileName(File.FileName) that return only file name. Example:
Dim File As HttpPostedFile = context.Request.Files("txtFile")
' let's FileName is "d:\temp\1.txt"
Dim FileName As String = Path.GetFileName(File.FileName)
' FileName will be "1.txt"
来源:https://stackoverflow.com/questions/382464/httppostedfile-filename-different-from-ie