我有以下代码在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
}
}
}
Run Code Online (Sandbox Code Playgroud)
在我的视图中我有这个:
@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" />
}
Run Code Online (Sandbox Code Playgroud)
如果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
}
}
}
Run Code Online (Sandbox Code Playgroud)
我还建议您查看以下关于在ASP.NET MVC中上传文件的博客文章.
| 归档时间: |
|
| 查看次数: |
3326 次 |
| 最近记录: |