c# - System.IO.File.Exists(fpath)在Chrome和Firefox中返回false

标签 c# asp.net-mvc-3

我有以下代码可在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 &nbsp;&nbsp;&nbsp;</text>
    <input type="file" name="file" id="file" /> <text> &nbsp; &nbsp; &nbsp;</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/

相关文章:

c# - MVC3 - Ajax Action 链接 - OnBegin,onComplete

c# - Entity Framework : where field starts with number

asp.net-mvc-3 - MVC找出当前Web请求是针对 Controller /操作还是静态资源

c# - 为什么我在使用 FileStream.Write 时会越界?

c# - 安装 Visual Web Developer 2010 时出现问题?

c# - 从 Master 更新内容页面

c# - 反序列化大型 json 对象的 JsonMaxLength 异常

ajax - AJAC MVC3 Request 对象和原始 Ajax 数据到底在哪里?

javascript - 如何从 CMD 命令行启动 Node.js 应用程序,并从另一个 .Net core 3.0 应用程序调用它?

c# - Active Directory 列表 OU