简体   繁体   English

在嵌入标记中渲染MVC Fileresult而不是物理URL

[英]Render MVC Fileresult in embed tag not the physical Url

I have a MVC method which returns the fileresult (returns the PDF file), I need to use the same url in src tag and show it in browser. 我有一个返回fileresult的MVC方法(返回PDF文件),我需要在src标签中使用相同的url并在浏览器中显示它。

For Example my sample code is below: 例如,我的示例代码如下:

public FileResult GetAttachment()
{
    return File(@"c:\sample.pdf", "application/pdf", "sample.pdf");
}

<embed src="/Home/GetAttachment" width="100%" height="1150" type="application/pdf"></embed>

I gave the actionname in the src of embed tag, not is there an work around to get the sample.pdf (File result) and render with in the browser. 我在embed标签的src中给出了actionname,而不是有一个解决方法来获取sample.pdf(文件结果)并在浏览器中渲染。

Try returning a FileStreamResult : 尝试返回FileStreamResult

public ActionResult GetAttachment()
{
    var fileStream = new FileStream(Server.MapPath("~/Content/files/sample.pdf"), 
                                     FileMode.Open,
                                     FileAccess.Read
                                   );
    var fsResult = new FileStreamResult(fileStream, "application/pdf");
    return fsResult;
}

Inside view: 内部视图:

<embed src="@Url.Action("GetAttachment", "Home")" width="100%" height="1150" type="application/pdf"></embed>

Ultimately how the pdf displays is going to be determined by the pdf viewer installed on the system and it's settings. 最终,pdf显示将如何由系统上安装的pdf查看器及其设置决定。 That being said you may be able to force it to render inline in some cases. 也就是说,在某些情况下,您可能会强制它呈现内联。 You could try overriding the content disposition with something like 您可以尝试用类似的东西覆盖内容处置

Response.Headers.Remove("Content-Disposition");
Response.Headers.Add("Content-Disposition", "inline; filename=sample.pdf");
return File(@"c:\sample.pdf", "application/pdf", "sample.pdf");

you may want two methods - one that renders inline and one the downloads or a bool parameter to determine rendering. 您可能需要两种方法 - 一种呈现内联,一种下载或bool参数来确定呈现。

You can try 你可以试试

public FileResult GetAttachment()
{
    byte[] contents = System.IO.File.ReadAllBytes(@"c:\sample.pdf");
    Response.AddHeader("Content-Disposition", "inline; filename=sample.pdf");
    return File(contents, "application/pdf");
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM