从HttpPostedFile获取文件路径 [英] getting file path from HttpPostedFile

查看:836
本文介绍了从HttpPostedFile获取文件路径的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试获取上载文件的文件路径,并且我使用的是HttpPostedFile,看来它不是获取路径名的一种选择.真的吗? 我该怎么办?

I am trying to get the file path of an uploading file and i am using HttpPostedFile and it doesn't seem that it is an option to get the path name. Is that true? How can i go about this?

foreach (string s in Request.Files)
            {
                HttpPostedFile file = Request.Files[s];
                string fileName = file.FileName;
                string filePath = Path.GetFullPath(fileName);
                string fileExtension = "";

                if (!string.IsNullOrEmpty(fileName))
                    fileExtension = Path.GetExtension(fileName);

                ....
            }

推荐答案

正如PKKG在评论中指出的那样,由于浏览器的安全性限制,这是不可能的. 他们只会告诉您上传文件的名称,而不是其路径.

As PKKG pointed out in a comment, this is not possible due to security restrictions by browsers. They will only tell you the name of the uploaded file, not the path to it.

例如,当尝试通过javascript捕获C:\fakepath\TestFile.xml时,谷歌浏览器会为您提供伪造的路径.

Also, for example, Google Chrome will give you a faked path when trying to grab it via javascript : C:\fakepath\TestFile.xml.

现在,我手头已经有了IE,我什至意识到,如果您抓住选定的值(例如通过document.forms.file.value),此将会通过javascript为您提供完整的正确路径.

Now that I have IE at hand, I even realized that this will give you the full correct path via javascript if you grab the selected value, for example via document.forms.file.value.

这是您不应该依赖的IMO不良行为.浏览器应该隐藏这些可信数据,您最好不要尝试破解可能会运行一段时间的解决方案,但这在不同浏览器甚至版本之间都不安全. 也许更好的问题是,无论如何,您打算如何处理客户的完整路径?可能还有另一种方法不需要客户端的路径.

This is IMO bad behaviour that you should not rely on. Browsers should hide this confidental data and you would probably be better off not trying to hack a solution that may work for a while, but it is not safe among different browsers or even versions. Maybe the better question is, what are you trying to do with the client's full path anyway? There might be another approach without the need of the client's path.

这篇关于从HttpPostedFile获取文件路径的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆