【发布时间】:2009-08-19 15:30:09
【问题描述】:
在我的一个 asp.net Web 应用程序中,我需要隐藏提供给用户的 pdf 文件的位置。
因此,我正在编写一个方法,该方法从 CMS 系统上的位置检索其二进制内容,然后将字节数组刷新给 Web 用户。
不幸的是,我在下载流时遇到错误:“无法打开文件,因为它已损坏”(或在 adobe reader 中打开文件时出现类似情况)。
问题 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();
}
【问题讨论】:
-
为什么不使用 Response.WriteFile 方法?
-
该文件在文件系统中并不真正存在。
-
更清楚一点:该文件存在于 CMS 数据库中。它是 url 可寻址的,但我无法真正从文件系统中检索文件。
-
啊,我错过了那部分。如何删除内容长度?另外,为什么你需要 string.Format("inline;filename=file.pdf") ?
-
不幸的是,删除没有区别:(
标签: asp.net filestream