【问题标题】:Show file in web browser在网络浏览器中显示文件
【发布时间】:2013-10-24 15:55:26
【问题描述】:

我收到了包含 PDF 文件的回复

HttpWebResponse res = (HttpWebResponse)HttpWRequest.GetResponse();
Stream pdf = res.GetResponseStream();

我想在网络浏览器上显示此 PDF 而不将其保存在文件中。我怎么能这样做?

【问题讨论】:

标签: c# asp.net


【解决方案1】:

我正在使用以下代码并且工作正常。

public static void SendDataByteFileToClient(HttpContext context, byte[] data, string fileName, string contentType, bool clearHeaders = true)
        {

            if (clearHeaders)
            {
                context.Response.Clear();
                context.Response.ClearHeaders();
            }

            context.Response.BufferOutput = true;
            context.Response.ContentType = contentType;

            context.Response.AddHeader("Content-Disposition", "inline; filename=" + fileName);
            context.Response.AddHeader("Content-Length", data.Length.ToString());

            if (BrowserHelper.IsOfType(BrowserTypeEnum.IE) && BrowserHelper.Version < 9)
            {
                context.Response.Cache.SetCacheability(HttpCacheability.Private);
                context.Response.Cache.SetMaxAge(TimeSpan.FromMilliseconds(1));
            }
            else
            {
                context.Response.Cache.SetCacheability(HttpCacheability.NoCache);//IE set to not cache
                context.Response.Cache.SetNoStore();//Firefox/Chrome not to cache
                context.Response.Cache.SetExpires(DateTime.UtcNow); //for safe measure expire it immediately
            }

            if (data.Length > 0)
            {
                context.Response.BinaryWrite(data);
            }

            context.Response.End();
        }

【讨论】:

    【解决方案2】:
    HttpWebResponse res = (HttpWebResponse)HttpWRequest.GetResponse();
    Stream pdfdata = res.GetResponseStream();
    string path = pdfdata.ToString();
        WebClient client = new WebClient();
        Byte[] buffer = client.DownloadData(path);
    
        if (buffer != null)
        {
            Response.ContentType = "application/pdf";
            Response.AddHeader("content-length", buffer.Length.ToString());
            Response.BinaryWrite(buffer);
            Response.End();
        }
    

    【讨论】:

    • 但是pdf不是字符串
    • pdf 是我们得到的响应,而不是原始 pdf
    • 我希望这是常识。但为了你的幸福,我编辑了它。
    • 下一次我坚持一步一步编写整个程序,没有任何一个分号丢失。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-06-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-04-10
    • 1970-01-01
    相关资源
    最近更新 更多