我有以下代码可在Internet Explorer中使用,但不能在Firefox和Google Chrome中使用。
public ActionResult LogoForm(HttpPostedFileBase file)
{
if (file != null)
{
string fpath = file.FileName;
if (System.IO.File.Exists(fpath))
{
// Logic comes here
}
}
}
在我看来,我有:
@using (Html.BeginForm("LogoForm", "LogoEditor", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
<text>Logo Image </text>
<input type="file" name="file" id="file" /> <text> </text>
<input type="submit" name="upload" value="Upload" />
}
对于Firefox和Chrome中的任何文件,“ if(System.IO.File.Exists(fpath))”行始终返回false!找不到文件。为什么这样?
最佳答案
file.FileName
包含客户端计算机上而不是服务器上的文件路径。您不应在服务器上使用它。之所以在IE中起作用,是因为IE恰巧将文件的完整路径发送到服务器,并且因为您在客户端和服务器上都在同一台计算机上运行它。出于安全原因,Chrome和FF从不发送文件路径。 IIRC他们将虚拟路径发送到任何地方都不存在的服务器。当您在IIS中部署应用程序并远程访问它时,这对IE均不起作用。
您永远不要依赖file.FileName
的路径部分。您只应提取文件名,然后将其与服务器上的某些路径连接起来:
例如
[HttpPost]
public ActionResult LogoForm(HttpPostedFileBase file)
{
if (file != null)
{
string path = Path.GetFileName(file.FileName);
string fileName = Path.Combine(Server.MapPath("~/App_Data"), path);
if (File.Exists(fileName))
{
// logic comes here
}
}
}
我还建议您检查有关在ASP.NET MVC中上传文件的following blog post。
关于c# - System.IO.File.Exists(fpath)在Chrome和Firefox中返回false,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9295164/