在我的一个 asp.net Web 应用程序中,我需要隐藏提供给用户的 pdf 文件的位置。
因此,我正在编写一种方法,该方法从 CMS 系统上的位置检索其二进制内容,然后将字节数组刷新给 Web 用户。
不幸的是,我在下载流时遇到错误:“无法打开文件,因为它已损坏”(或类似的东西,在 adobe 阅读器中打开文件时)。
问题1:我做错了什么?问题2:我可以使用这种方法下载大文件吗?
private void StreamFile(IItem documentItem)
{
//CMS vendor specific API
BinaryContent itemBinaryContent = documentItem.getBinaryContent();
//Plain old .NET
Stream fileStream = itemBinaryContent.getContentStream();
var len = itemBinaryContent.getContentLength();
SendStream(fileStream, len, itemBinaryContent.getContentType());
}
private void SendStream(Stream stream, int contentLen, string contentType)
{
Response.ClearContent();
Response.ContentType = contentType;
Response.AppendHeader("content-Disposition", string.Format("inline;filename=file.pdf"));
Response.AppendHeader("content-length", contentLen.ToString());
var bytes = new byte[contentLen];
stream.Read(bytes, 0, contentLen);
stream.Close();
Response.BinaryWrite(bytes);
Response.Flush();
}