2015-09-17 78 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阅读器插件缺失/浏览器是旧的..等)。

相关问题