2015-09-17 80 views
0

我正在從MVC項目調用Web API。點擊一個按鈕後,Web API將返回要在瀏覽器中直接顯示的PDF文件。我的問題是,當我點擊鏈接時,它下載PDF文件並在左下角顯示圖標,我必須點擊它並在acrobat中打開PDf。我如何通過點擊鏈接直接在瀏覽器中打開PDF?下載PDF文件並在MVC項目中直接在瀏覽器中顯示

這是我在MVC項目代碼,打開PDF:

[HttpGet] 
public FileResult openPdf(string name) 
{ 
    byte[] pdfByte = DownloadFile(); 
    return File(pdfByte, "application/pdf", name); 
} 

internal byte[] DownloadFile() 
{ 
    string serverUrl = "http://localhost/GetPdf?Number=3671"; 
    var client = new System.Net.WebClient(); 
    client.Headers.Add("Content-Type", "application/pdf"); 
    return client.DownloadData(serverUrl); 
} 

這是我的Web API返回PDF格式的方法:

public HttpResponseMessage GetPdfNameByRemRef(string RemoteRefNumber) 
{ 
    var stream = new MemoryStream(); 
    var response = new HttpResponseMessage(HttpStatusCode.OK) 
    { 
     Content = new ByteArrayContent(stream.GetBuffer()) 
    }; 

    byte[] fileBytes = System.IO.File.ReadAllBytes(@"C:\Pdf\CreditApplication_08192006_102714AM_et montis.pdf"); 

    response.Content = new ByteArrayContent(fileBytes); 
    response.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment"); 
    response.Content.Headers.ContentDisposition.FileName = customerInfo.Application_Filename; 
    response.Content.Headers.ContentType = new MediaTypeHeaderValue("application/pdf"); 

    return response; 
} 

回答

0

你可以嘗試添加Content-Disposition標頭值inline

Response.AddHeader("Content-Disposition", "inline;filename=fileName.pdf"); 

但是,不同的瀏覽器和您所服務的文件類型的行爲可能會有所不同。如果Content-Disposition設置爲inline,瀏覽器將嘗試在瀏覽器中打開該文件,但如果文件類型未知(例如.rar,.zip,.pdf /當pdf閱讀器插件缺失/瀏覽器是舊的..等)。

相關問題