在 MVC 4 Razor 应用程序中创建指向内部驱动器上物理文件的下载链接

本文关键字:驱动器 文件 链接 下载 内部 Razor MVC 应用程序 创建 | 更新日期: 2023-09-27 18:37:20

我正在尝试在 MVC4 应用程序中执行此操作:

@foreach (var item in Model)
{
    <tr>
        <td><a href="@item.DownloadUrl">Download Document</a></td>
    </tr>
}

视图呈现良好,但是当我单击链接时,不会下载任何内容。

当我将鼠标悬停在@item.DownloadUrl上时,我可以看到它的值为:C:'Websites'Documents'105.pdf,这是正确的。

当我将鼠标悬停在链接本身上时,我会看到这个 URL 而不是上面的:file:///C:/Websites/Documents/105.pdf ,这表明"file:///"已被添加到开头。

我想知道如何正确地做到这一点。我知道在我可以让应用程序链接访问本地驱动器文件之前可能有一些 IIS 配置,但这显然到目前为止无关紧要,还是吗?我正在调试模式下在Visual Studio中运行它。

注意:@item.DownloadUrl 是在运行时基于一些代码生成的,例如:

while (Reader.Read())
{
    la.DownloadUrl = Path.Combine(DocumentsLocation, Reader["Id"] + ".pdf");
}

谢谢。

在 MVC 4 Razor 应用程序中创建指向内部驱动器上物理文件的下载链接

这就是我最终解决问题的方式:

byte[] fileBytes = System.IO.File.ReadAllBytes(System.IO.Path.Combine(DocumentsLocation, name + ".pdf"));
string fileName = name + ".pdf";
return File(fileBytes, System.Net.Mime.MediaTypeNames.Application.Octet, fileName);

感谢所有做出贡献的人。

您确实需要使用Server.MapPath链接到服务器上的远程文件。您现在正在做的是链接到客户端计算机上的物理文件。

HttpContext.Current.Server.MapPath(Path.Combine(DocumentsLocation, Reader["Id"] + ".pdf"));