System.IO.File.Exists(fpath)在Chrome和Firefox中返回false [英] System.IO.File.Exists(fpath) returns false in Chrome and Firefox

查看:106
本文介绍了System.IO.File.Exists(fpath)在Chrome和Firefox中返回false的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下代码可在Internet Explorer中使用,但不能在Firefox和Google Chrome中使用.

I have the following code which works in Internet Explorer, but not in Firefox and 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!找不到文件.为什么这样?

In case of any file in Firefox and Chrome, the line 'if (System.IO.File.Exists(fpath))' always returns false! It doesn't find the file. Why so?

推荐答案

file.FileName包含客户端计算机上而不是服务器上的文件路径.您不应在服务器上使用它.之所以在IE中运行,是因为IE恰巧将文件的完整路径发送到服务器,并且由于您在同一台计算机上运行客户端和服务器.出于安全原因,Chrome和FF从不发送文件路径. IIRC他们将虚拟路径发送到任何地方都不存在的服务器.当您在IIS中部署应用程序并对其进行远程访问时,这也不适用于IE.

file.FileName contains the file path on the client computer, not on the server. You should not use it on the server. The reason this works in IE is because IE happens to send the full path to the file to the server and since you are running both the client and the server on the same machine it works. Chrome and FF for security reasons never send the file path. IIRC they send a dummy path to the server that doesn't exist anywhere. This won't work with IE neither when you deploy your application in IIS and access it remotely.

您永远不应依赖file.FileName的路径部分.您只应提取文件名,然后将其与服务器上的路径连接起来:

You should never rely on the path portion of file.FileName. You should only extract the filename and then concatenate it with some path on the server:

例如

[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中上传文件的帖子.

这篇关于System.IO.File.Exists(fpath)在Chrome和Firefox中返回false的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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