2010-10-05 57 views
1

使用下面的代码ASP.NET显示PDF文件的用户,而不是“另存为”对话框

Context.Response.Clear(); 
Context.Response.ContentType = "application/pdf"; 
Context.Response.TransmitFile(optionEntityCmd.PathToSave); 
Context.Response.End(); 

此代码显示另存为浏览器对话框我的ASP.NET应用程序返回PDF文件的用户,是否有可能代替另存为对话框直接在浏览器中加载PDF文件?

回答

5

你可以追加Content-Disposition头:

Context.Response.AppendHeader(
    "Content-Disposition", 
    "inline; filename=foo.pdf" 
); 
+0

是的,它已经加入,我只是错过了张贴在这里 Context.Response.AddHeader(“内容处置”,“附件;文件名=” +文件名); – Tomas 2010-10-05 07:16:54

+0

哎呀,对不起。你想要它内联,而不是附件。我误解了你的问题。请参阅我的更新。 – 2010-10-05 07:17:50

+0

“inline”诀窍,非常感谢Darin :) – Tomas 2010-10-05 07:24:31

0

它是一个动态创建的文件?如果没有,你可以超链接或Response.Redirect它我相信。

+0

的文件存储在硬盘驱动器,但我并不想举办文件在IIS上的URL存储,我想隐藏实际的文件位置,所以我使用Context.Response.TransmitFile。我不确定你的建议如何解决问题。 – Tomas 2010-10-05 06:57:48

0

我不知道是肯定的经典asp.net,但使用MVC,它流给用户你想要做什么:

MemoryStream stream = PDF.GeneratePDFByStream(); 
stream.Flush(); //Always catches me out 
stream.Position = 0; //Not sure if this is required 
return stream; 

public static MemoryStream GeneratePDFByStream() { 
    var doc1 = new Document(); 
    //use a variable to let my code fit across the page... 
    string path = AppDomain.CurrentDomain.BaseDirectory + "PDFs"; 
    MemoryStream stream = new MemoryStream(); 
    PdfWriter writer = PdfWriter.GetInstance(doc1, stream); 
    writer.CloseStream = false; 

    // Actual Writing 
    doc1.Open(); 
    // writing comes here, you will probably just load the PDF in a stream? 
    doc1.Close(); 

    return stream; 
} 

而且你的MVC控制器返回的东西像

return File(GetPDFStream(id), "application/pdf"); 

所以,我知道这不是你正在寻找的确切答案,但也许你应尽量流的PDF给用户,因为它会在新标签中打开它,因为我测试过它远。

从我的头顶,你应该得到的东西,如:

Response.Clear(); 
Response.ContentType = "application/pdf"; 
Response.OutputStream.Write(objMemoryStream.ToArray(), 0,   
Convert.ToInt32(objMemoryStream.Length)); 
Response.Flush(); 
try { Response.End(); } catch{} 
相关问题