C#下载并查看pdf文件

时间:2015-06-24 07:50:33

标签: c# asp.net pdf

我想在浏览器中单击下载并查看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);
}

1 个答案:

答案 0 :(得分:0)

像这样 -

如果要下载并打开服务器文件调用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);
        }

    }