1. 程式人生 > 實用技巧 >.NetMvc從http或本地下載pdf檔案

.NetMvc從http或本地下載pdf檔案

1、幫助類

 1 public static class PdfHelper
 2     {
 3         #region 從http連結下載
 4         public static void Download(string url, string name, System.Web.Mvc.Controller controller)
 5         {
 6             var bytes = GetByteByRemoteURL(url);
 7             controller.Response.Charset = "UTF-8";
 8
controller.Response.ContentType = "application/octet-stream"; 9 controller.Response.ContentEncoding = Encoding.Default; 10 controller.Response.AddHeader("Content-Disposition", "attachment; filename=" + name.Replace(" ", "") + ".pdf"); 11 controller.Response.BinaryWrite(bytes);
12 controller.Response.Flush(); 13 controller.Response.End(); 14 } 15 #endregion 16 17 #region 呼叫本地檔案使用返回pdfbyte陣列 18 19 /// <summary> 20 /// 呼叫本地檔案使用返回pdfbyte陣列 21 /// </summary> 22 /// <param name="srcPdfFile">‘D:\in2434341555551.pdf’
</param> 23 /// <returns></returns> 24 25 public static byte[] GetSignaturePDFByte(string srcPdfFile) 26 { 27 using (FileStream fsRead = new FileStream(srcPdfFile, FileMode.Open, FileAccess.Read, FileShare.Read)) 28 { 29 int fsLen = (int)fsRead.Length; 30 byte[] hebyte = new byte[fsLen]; 31 fsRead.Read(hebyte, 0, hebyte.Length); 32 return hebyte; 33 } 34 } 35 36 #endregion 呼叫本地檔案使用返回pdfbyte陣列 37 38 #region 從網站上下載pdf,轉化為位元組流 39 /// <summary> 40 /// 從網站上下載pdf,轉化為位元組流 41 /// </summary> 42 /// <param name="srcPdfFile">檔案地址:'https://******/group2/M00/00/04/wKj-mlpcoZ2IUbK5AACrpaV6k98AAAB6gAAAAAAAKu9562.pdf'</param> 43 44 /// <returns></returns> 45 public static Byte[] GetByteByRemoteURL(string srcPdfFile) 46 { 47 byte[] arraryByte; 48 HttpWebRequest req = (HttpWebRequest)HttpWebRequest.Create(srcPdfFile); 49 req.Method = "GET"; 50 using (WebResponse wr = req.GetResponse()) 51 { 52 StreamReader responseStream = new StreamReader(wr.GetResponseStream(), Encoding.UTF8); 53 int length = (int)wr.ContentLength; 54 byte[] bs = new byte[length]; 55 56 HttpWebResponse response = wr as HttpWebResponse; 57 Stream stream = response.GetResponseStream(); 58 59 //讀取到記憶體 60 MemoryStream stmMemory = new MemoryStream(); 61 byte[] buffer1 = new byte[length]; 62 int i; 63 //將位元組逐個放入到Byte 中 64 while ((i = stream.Read(buffer1, 0, buffer1.Length)) > 0) 65 { 66 stmMemory.Write(buffer1, 0, i); 67 } 68 arraryByte = stmMemory.ToArray(); 69 stmMemory.Close(); 70 } 71 return arraryByte; 72 } 73 74 #endregion 從網站上下載pdf,轉化為位元組流 75 76 }

2、呼叫方法

1 public ActionResult Down()
2         {            
3             PdfHelper.Download("http連結", "匯出檔名字", this);
4             return new EmptyResult();
5         }

3、前端使用

1  function Download() {
2         location.href = "/xx/down";
3     }