背景及需求
項(xiàng)目使用的是MVC4框架,其中有一個(gè)功能是根據(jù)設(shè)置生成PDF文件,并在點(diǎn)擊時(shí)直接預(yù)覽。
實(shí)現(xiàn)過(guò)程
1、第一版實(shí)現(xiàn)代碼:
HTML內(nèi)容
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
|
@{ Layout = null; } <!DOCTYPE html> < html > < head > < meta name = "viewport" content = "width=device-width" /> < title >Index</ title > </ head > < body > < div > @Html.ActionLink("預(yù)覽PDF","GetPdf",null,new { target="_blank"}) </ div > </ body > </ html > |
控制器代碼
1
2
3
4
|
public ActionResult GetPdf() { return new FilePathResult( "~/content/The Garbage Collection Handbook.pdf" , "application/pdf" ); } |
缺點(diǎn):標(biāo)題和文件下載時(shí)名稱(chēng)不是很友好。
1、第二版實(shí)現(xiàn)代碼:
我們做了2件事情:
1、讓下載彈出框能顯示友好的下載文件名。
2、讓瀏覽器中的其他兩個(gè)顯示GetPdf的地方也顯示友好的內(nèi)容。
自定義ActionFilter,對(duì)Header進(jìn)行修改,變?yōu)閮?nèi)聯(lián)。(直接這么替換不知道會(huì)不會(huì)有隱患。)
1
2
3
4
5
6
7
8
9
10
11
|
public class MyPdfActionFilter : ActionFilterAttribute { public override void OnResultExecuted(ResultExecutedContext filterContext) { //Content-Disposition=attachment%3b+filename%3d%22The+Garbage+Collection+Handbook.pdf%22} var filerHeader = filterContext.HttpContext.Response.Headers.Get( "Content-Disposition" ); if (! string .IsNullOrEmpty(filerHeader) && filerHeader.Substring(0, "attachment" .Length).ToLower().Equals( "attachment" )) { filterContext.HttpContext.Response.Headers[ "Content-Disposition" ] = "inline" + filerHeader.Substring( "attachment" .Length, filerHeader.Length - "attachment" .Length); } } } |
自定義ActionNameSelector實(shí)現(xiàn)對(duì)Action名稱(chēng)的攔截和判斷。
1
2
3
4
5
6
7
|
public class MyActionNameSelecter : ActionNameSelectorAttribute { public override bool IsValidName(ControllerContext controllerContext, string actionName, MethodInfo methodInfo) { return actionName.Contains( "-PDF文件預(yù)覽" ); } } |
控制器內(nèi)代碼修改如下
1
2
3
4
5
6
7
8
9
|
[MyActionNameSelecter] [MyPdfActionFilter] public ActionResult GetPdf() { return new FilePathResult( "~/content/The Garbage Collection Handbook.pdf" , "application/pdf" ) //增加FileDownloadName設(shè)置,但是這會(huì)讓內(nèi)容以附件的形式響應(yīng)到瀏覽器(具體參考文件響應(yīng)模式:內(nèi)聯(lián)和附件)。 //文件變成被瀏覽器下載。 { FileDownloadName = "The Garbage Collection Handbook.pdf" }; } |
頁(yè)面內(nèi)容修改如下
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
|
@{ Layout = null; } <!DOCTYPE html> < html > < head > < meta name = "viewport" content = "width=device-width" /> < title >Index</ title > </ head > < body > < div > @* 第二個(gè)參數(shù)可能是一個(gè)動(dòng)態(tài)生成的內(nèi)容,需要ACTION中增加名稱(chēng)選擇攔截,所以自定義了一個(gè)ActionNameSelectorAttribute類(lèi)滿(mǎn)足要求。 *@ @Html.ActionLink("預(yù)覽PDF", "The Garbage Collection Handbook-PDF文件預(yù)覽", null,new { target="_blank"}) </ div > </ body > </ html > |
最終效果
以上就是本文的全部?jī)?nèi)容,希望本文的內(nèi)容對(duì)大家的學(xué)習(xí)或者工作能帶來(lái)一定的幫助,同時(shí)也希望多多支持服務(wù)器之家!
原文鏈接:http://www.cnblogs.com/cnlizhipeng/p/MVC-PDF.html