尝试使用asp.net流式传输PDF文件会产生“损坏的文件”

前端之家收集整理的这篇文章主要介绍了尝试使用asp.net流式传输PDF文件会产生“损坏的文件”前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
在我的一个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,contentLen);
        stream.Close();
        Response.BinaryWrite(bytes);
        Response.Flush();
    }
@H_404_11@

解决方法

这是我使用的方法.这会传回一个附件,因此IE会生成一个打开/保存对话框.我也碰巧知道文件不会大于1M,所以我相信有更简洁的方法可以做到这一点.

我对PDF有类似的问题,我意识到我绝对不得不使用二进制流和ReadBytes.任何有字符串的东西搞砸了.

Stream stream = GetStream(); // Assuming you have a method that does this.
BinaryReader reader = new BinaryReader(stream);

HttpResponse response = HttpContext.Current.Response;
response.ContentType = "application/pdf";
response.AddHeader("Content-Disposition","attachment; filename=file.pdf");
response.ClearContent();
response.OutputStream.Write(reader.ReadBytes(1000000),1000000);

// End the response to prevent further work by the page processor.
response.End();
@H_404_11@ @H_404_11@ 原文链接:https://www.f2er.com/aspnet/246625.html

猜你在找的asp.Net相关文章