我有一个网站,其中有一堆预先创建并存放在网络服务器上的PDF.
我不想让用户只输入一个URL并获取PDF文件(即http://MySite/MyPDFFolder/MyPDF.pdf)
我想只允许在加载它们并显示它们时查看它们.
我之前做过类似的事.我使用PDFSharp在内存中创建PDF,然后将其加载到这样的页面:
protected void Page_Load(object sender, EventArgs e)
{
try
{
MemoryStream streamDoc = BarcodeReport.GetPDFReport(ID, false);
// Set the ContentType to pdf, add a header for the length
// and write the contents of the memorystream to the response
Response.ContentType = "application/pdf";
Response.AddHeader("content-length", Convert.ToString(streamDoc.Length));
Response.BinaryWrite(streamDoc.ToArray());
//End the response
Response.End();
streamDoc.Close();
}
catch (NullReferenceException)
{
Communication.Logout();
}
}
Run Code Online (Sandbox Code Playgroud)
我试图使用此代码从文件中读取,但无法弄清楚如何让MemoryStream读取文件.
我还需要一种方法来说"/ MyPDFFolder"路径是不可浏览的.
谢谢你的任何建议
要将PDF文件从磁盘加载到缓冲区:
byte [] buffer;
using(FileStream fileStream = new FileStream(Filename, FileMode.Open))
{
using (BinaryReader reader = new BinaryReader(fileStream))
{
buffer = reader.ReadBytes((int)reader.BaseStream.Length);
}
}
Run Code Online (Sandbox Code Playgroud)
然后你可以这样创建MemoryStream
:
using (MemoryStream msReader = new MemoryStream(buffer, false))
{
// your code here.
}
Run Code Online (Sandbox Code Playgroud)
但是如果你已经将数据存储在内存中,则不需要MemoryStream
.而是这样做:
Response.ContentType = "application/pdf";
Response.AddHeader("Content-Length", buffer.Length.ToString());
Response.BinaryWrite(buffer);
//End the response
Response.End();
streamDoc.Close();
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
645 次 |
最近记录: |