Core 2.0 MVC - 如何链接到保存在文件系统上的动态PDF

时间:2018-02-13 20:03:12

标签: asp.net-mvc asp.net-mvc-4 pdf asp.net-core

我有一个.NET Core 2.0 MVC项目。我的一个模型有一个名为PDFUpload的NotMapped IFormFile字段,它接受上传并将文件保存到根目录外的文件系统上的某个位置,该路径保存在PDF字段中。当用户点击特定URL时,PDF需要在浏览器中显示或下载。我的Details.cshtml视图目前只显示路径

 @Html.DisplayFor(model => model.PDF)

如何将其转换为将从特定网址提供文件的实际链接,而不显示路径?

更新:这是工作版

if (System.IO.File.Exists(pdf))
{
    var stream = new FileStream(pdf, FileMode.Open);
    // send the file to the browser
    stream.Position = 0;
    //return File(stream,"application/pdf","filename.pdf") //- will force download
    return new FileStreamResult(stream, "application/pdf");//will display in browser        
}

2 个答案:

答案 0 :(得分:1)

您可以执行控制器操作来提供文件。您需要一些方法来识别文件并使用该标识符来定位它。像这样的东西(我使用了slug):

public IActionResult GimmeThePdf(string slug)
{
    string filePathToPdf = // look this up in a database given the slug, map the path, etc.
    // open the file for reading
    using (Stream stream = new FileStream(filePathToPdf, FileMode.Open)
    {
        // send the file to the browser
        return File(stream, "application/pdf");
    }
}

然后在你看来:

//generate the link, could also do this with tag helpers
@Html.ActionLink("download the pdf", "GimmeThePdf", "YourController", new {slug = Model.PdfSlug});

这将生成如下内容:

<a href="http://yoursite.com/YourController/GimmeThePdf?slug=...">download the pdf</a>

答案 1 :(得分:1)

我只是想添加到@Becuzz Answer。我在处理文件时遇到麻烦,在这里MVC FileStreamResult and handling other

找到了答案
public IActionResult GimmeThePdf(string slug)
{
    string filePathToPdf = // look this up in a database given the slug, map the path, etc.

    // open the file for reading
    FileStream stream = new FileStream(filePathToPdf, FileMode.Open);

    // Register this stream for disposal after response is finished.
    HttpContext.Response.RegisterForDispose(stream);

    // send the file to the browser
    //return File(stream,"application/pdf","filename.pdf") //- will force download
    return File(stream, "application/pdf");
}