首页 > 代码库 > ASP.NET 实现Base64文件流下载PDF

ASP.NET 实现Base64文件流下载PDF

因为业务需要调用接口获取的是 Base64文件流 需要提供给客户下载PDF文档

源码部分借鉴网上,具体地址忘记了。

 //Base64文件流             byte[] buffer = Convert.FromBase64String(decodedString);             System.IO.Stream iStream = new System.IO.MemoryStream(buffer);            try            {                int length;                long dataToRead;                string filename = sn + ".pdf";//保存的文件名称                dataToRead = iStream.Length;                Response.Clear();                Response.ClearHeaders();                Response.ClearContent();                Response.ContentType = "application/pdf"; //文件类型                  Response.AddHeader("Content-Length", dataToRead.ToString());//添加文件长度,进而显示进度                  Response.AddHeader("Content-Disposition", "attachment; filename=" + HttpUtility.UrlEncode(filename, System.Text.Encoding.UTF8));                while (dataToRead > 0)                {                    if (Response.IsClientConnected)                    {                        length = iStream.Read(buffer, 0, 10000);                        Response.OutputStream.Write(buffer, 0, length);                        Response.Flush();                        buffer = new Byte[10000];                        dataToRead = dataToRead - length;                    }                    else                    {                        dataToRead = -1;                    }                }            }            catch (Exception ex)            {                Response.Write("文件下载时出现错误!");            }            finally            {                if (iStream != null)                {                    iStream.Close();                }                //结束响应,否则将导致网页内容被输出到文件,进而文件无法打开                   Response.Flush();                Response.End();            }

  

ASP.NET 实现Base64文件流下载PDF