我希望将 SharePoint 2003 文档库中的文件流式传输到浏览器。基本上,想法是将文件作为流打开,然后将文件流“写入”响应,指定内容类型和内容配置 header 。 Content disposition 用于保存文件名,内容类型当然可以提示浏览器打开什么应用程序来查看文件。
这在开发环境和 UAT 环境中工作得很好。然而,在生产环境中,事情并不总是像预期的那样工作,而是只适用于 IE6/IE7。 FF 在所有环境中都能很好地工作。
请注意,在生产环境中启用并普遍使用 SSL。 (当生产环境不使用SSL时,文件流,按预期命名,并正确显示。)
这是一个代码片段:
System.IO.FileStream fs = new System.IO.FileStream(Server.MapPath(".") + "\\" + "test.doc", System.IO.FileMode.Open);
long byteNum = fs.Length;
byte[] pdfBytes = new byte[byteNum];
fs.Read(pdfBytes, 0, (int)byteNum);
Response.AppendHeader("Content-disposition", "filename=Testme.doc");
Response.CacheControl = "no-cache";
Response.ContentType = "application/msword; charset=utf-8";
Response.Expires = -1;
Response.OutputStream.Write(pdfBytes, 0, pdfBytes.Length);
Response.Flush();
Response.Close();
fs.Close();
正如我所说,此代码片段在开发机器和 UAT 环境中运行良好。将打开一个对话框,要求保存、查看或取消 Testme.doc。但在生产环境中,只有在使用 SSL 时,IE 6 和 IE7 才不会使用附件的名称。相反,它使用发送流的页面名称 testheader.apx,然后抛出错误。
IE 确实提供了一个高级设置“不将加密的页面保存到磁盘”。
我怀疑这是问题的一部分,服务器告诉浏览器不要缓存文件,而 IE 启用了“不将加密的页面保存到磁盘”。
是的,我知道对于较大的文件,上面的代码片段将是内存的主要拖累,并且这种实现将是有问题的。所以真正的最终解决方案不会将整个文件打开到单个字节数组中,而是将文件作为流打开,然后将文件以一口大小的 block (例如,大约 10K 大小)发送给客户端。
还有其他人有过通过 ssl“流式传输”二进制文件的类似经历吗?有什么建议或建议吗?
最佳答案
这可能真的很简单,不管你信不信我今天编写了完全相同的代码,我认为问题可能是内容配置没有告诉浏览器它是一个附件,因此能够被保存。
Response.AddHeader("Content-Disposition", "attachment;filename=myfile.doc");
我没有在下面包含我的代码,因为我知道它适用于 https://
private void ReadFile(string URL)
{
try
{
string uristring = URL;
WebRequest myReq = WebRequest.Create(uristring);
NetworkCredential netCredential = new NetworkCredential(ConfigurationManager.AppSettings["Username"].ToString(),
ConfigurationManager.AppSettings["Password"].ToString(),
ConfigurationManager.AppSettings["Domain"].ToString());
myReq.Credentials = netCredential;
StringBuilder strSource = new StringBuilder("");
//get the stream of data
string contentType = "";
MemoryStream ms;
// Send a request to download the pdf document and then get the response
using (HttpWebResponse response = (HttpWebResponse)myReq.GetResponse())
{
contentType = response.ContentType;
// Get the stream from the server
using (Stream stream = response.GetResponseStream())
{
// Use the ReadFully method from the link above:
byte[] data = ReadFully(stream, response.ContentLength);
// Return the memory stream.
ms = new MemoryStream(data);
}
}
Response.Clear();
Response.ContentType = contentType;
Response.AddHeader("Content-Disposition", "attachment;");
// Write the memory stream containing the pdf file directly to the Response object that gets sent to the client
ms.WriteTo(Response.OutputStream);
}
catch (Exception ex)
{
throw new Exception("Error in ReadFile", ex);
}
}
关于asp.net - 用于预览的 SharePoint 流文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52702/