我可以显示PDF,但不允许链接到它的网站? [英] Can I display a PDF, but not allow linking to it in a website?
问题描述
我有一个网站,有一堆是pre-创建并坐在网络服务器。
I have a website that has a bunch of PDFs that are pre-created and sitting on the webserver.
我不希望允许用户只需键入网址并获得PDF文件(即 HTTP: //MySite/MyPDFFolder/MyPDF.pdf )
I don't want to allow a user to just type in a URL and get the PDF file (ie http://MySite/MyPDFFolder/MyPDF.pdf)
我想只允许当我加载它们,它们显示它们进行查看。
I want to only allow them to be viewed when I load them and display them.
我以前做过类似的事情。我用PDFSharp在内存中创建PDF文件,然后将其加载到页面这样的:
I have done something similar before. I used PDFSharp to create a PDF in memory and then load it to a page like this:
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();
}
}
我试图用这个code从文件中读取,但无法弄清楚如何让一个MemoryStream在一个文件中读取。
I tried to use this code to read from a file, but could not figure out how to get a MemoryStream to read in a file.
我还需要一种方式说,/ MyPDFFolder路径是不可浏览。
I also need a way to say that the "/MyPDFFolder" path is non-browsable.
感谢您的任何建议。
推荐答案
要加载从磁盘PDF文件到缓冲区:
To load a PDF file from the disk into a buffer:
byte [] buffer;
using(FileStream fileStream = new FileStream(Filename, FileMode.Open))
{
using (BinaryReader reader = new BinaryReader(fileStream))
{
buffer = reader.ReadBytes((int)reader.BaseStream.Length);
}
}
然后,您可以创建的MemoryStream
是这样的:
using (MemoryStream msReader = new MemoryStream(buffer, false))
{
// your code here.
}
但是,如果你已经在内存中的数据,你不需要的MemoryStream
。相反,这样做:
Response.ContentType = "application/pdf";
Response.AddHeader("Content-Length", buffer.Length.ToString());
Response.BinaryWrite(buffer);
//End the response
Response.End();
streamDoc.Close();
这篇关于我可以显示PDF,但不允许链接到它的网站?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!