4

我的桌面上有一个文件供测试。我试图在一个看起来像这样的视图中显示它:

@{
    ViewBag.Title = "ShowFile";
}

<h2>ShowFile</h2>

我用于控制器的代码是:

   [HttpGet]
        public ActionResult ShowFile(string path)
        {
            path = @"C:\Documents and Settings\nickla\Desktop\nlamarca_06_15.pdf";

            return File(path, "application/pdf", "nlamarca_06_15.pdf");
        }

当我运行此代码时,视图会显示“未定义”关于这里可能出现什么问题的任何想法?

4

3 回答 3

7

您似乎没有在路径中指定文件名:

public ActionResult ShowFile(string filename)
{
    var path = @"C:\Documents and Settings\nickla\Desktop";
    var file = Path.Combine(path, filename);
    file = Path.GetFullPath(file);
    if (!file.StartsWith(path))
    {
        // someone tried to be smart and sent 
        // ?filename=..\..\creditcard.pdf as parameter
        throw new HttpException(403, "Forbidden");
    }
    return File(file, "application/pdf");
}
于 2012-07-17T14:12:24.017 回答
2

您在路径中缺少文件名。你的路径只到目录。给出完整的 PDF 文件名。

public ActionResult ShowFile(string path)
{
   //not sure why you overwrote although you have a parameter to pass the path

    path = @"C:\Documents and Settings\nickla\Desktop\nlamarca_06_15.pdf";
    return File(path, "application/pdf", "nlamarca_06_15.pdf");
}

假设您在该特定目录中的 PDF 文件名是nlamarca_06_15.pdf

于 2012-07-17T14:12:44.307 回答
0

缺口,

乍一看似乎是路径问题(没有文件名,只有路径),请尝试:

[HttpGet]
public ActionResult ShowFile(string path)
{
    path = @"C:\Documents and Settings\nickla\Desktop\nlamarca_06_15.pdf";

    return File(path, "application/pdf", "pdf_download_name.pdf");
}

最后一个参数纯粹是您希望下载的文件在“命中”用户本地驱动器时给出的名称。

[编辑]我看到你已经更新了你的问题,这使到目前为止的所有建议都无效。我能看到的唯一补充是您可能没有处理路径参数的路由设置。这个问题可能是一个移动的目标:)

于 2012-07-17T14:12:36.863 回答