C#下载并查看pdf文件

本文关键字:pdf 文件 下载 | 更新日期: 2023-09-27 17:59:14

我想在浏览器中一键下载并查看pdf文件。。下载和查看代码都在不同的页面上工作但由于HttpContext.Current.Response的原因,它不能同时作用于按钮单击有什么建议吗

下面是代码

public static void DownloadFile(string filePath)
{
    try {
        HttpContext.Current.Response.ContentType = "application/octet-stream";
        HttpContext.Current.Response.AddHeader("Content-Disposition", "attachment; filename='"" + System.IO.Path.GetFileName(filePath) + "'"");
        HttpContext.Current.Response.Clear();
        HttpContext.Current.Response.WriteFile(filePath);
        HttpContext.Current.Response.End();
    } catch (Exception ex) {
    }
}

public static void ViewFile(string filePath)
{
    WebClient User = new WebClient();
    Byte[] FileBuffer = User.DownloadData(filePath);
    if (FileBuffer != null) {
        HttpContext.Current.Response.Clear();
        HttpContext.Current.Response.ContentType = "application/pdf";
        HttpContext.Current.Response.AddHeader("content-length", FileBuffer.Length.ToString());
        HttpContext.Current.Response.BinaryWrite(FileBuffer);
        HttpContext.Current.Response.End();
    }
    DownloadFile(filePath);
}

C#下载并查看pdf文件

类似的东西-

如果要下载并打开服务器文件,请调用SendFiletoBrowser。若要下载远程文件并在浏览器中显示,则调用OpenRemoteFileInBrowser方法。

public void SendFiletoBrowser(string path,string fileName)
    {
        try
        {
            MemoryStream ms = new MemoryStream();
            using (FileStream fs = File.OpenRead(Server.MapPath(path)))
            {
                fs.CopyTo(ms);
            }
            ms.Position = 0;
            OpenInBrowser(ms, fileName);
        }
        catch (Exception)
        {
            throw;
        }

    }
    public void OpenRemoteFileInBrowser(Uri destinationUrl, string fileName)
    {
        try
        {
            WebClient wc = new WebClient();
            using (MemoryStream stream = new MemoryStream(wc.DownloadData(destinationUrl.ToString())))
            {
                OpenInBrowser(stream, fileName);
            }
        }
        catch (Exception)
        {
            throw;
        }
    }
    private void OpenInBrowser(MemoryStream stream, string fileName)
    {
        byte[] buffer = new byte[4 * 1024];
        int bytesRead;
        bytesRead = stream.Read(buffer, 0, buffer.Length);
        Response.Buffer = false;
        Response.BufferOutput = false;
        Response.Clear();
        Response.ContentType = "application/octet-stream";
        Response.AppendHeader("Content-Disposition", "inline; filename=" + fileName);
        if (stream.Length != -1)
            Response.AppendHeader("Content-Length", stream.Length.ToString());
        while (bytesRead > 0 && Response.IsClientConnected)
        {
            Response.OutputStream.Write(buffer, 0, bytesRead);
            bytesRead = stream.Read(buffer, 0, buffer.Length);
        }
    }