C#下載http/https的pdf、excel等文件(非在線打開,繞開插件)


非本服務器文件,如PDF,excel等,下載一般是通過href=‘遠程文件的http或者https’的方式下載,但是如果瀏覽器已經有PDF插件了,則用href不是下載,而是在線打開了,影響體驗,所以遠程服務器文件下載改為后台的方式下載,可以繞開插件。代碼如下:

string url = hidFilePath.Value;//文件的地址:如http://emec.h.c/pdf/test.pdf
string filename = hidFileName.Value;//導出的文件名稱:如測試導出文件

//處理后綴
string[] _filename = url.Split('.');//得到文件后綴

long remoteFileLength = GetHttpLength(url);// 取得遠程文件長度

if (remoteFileLength == 745 || remoteFileLength == 0)
{
Page.ClientScript.RegisterClientScriptBlock(GetType(), "js", "<script>alert('遠程文件不存在');</script>");

return;
}

HttpWebRequest myRequest = (HttpWebRequest)HttpWebRequest.Create(url);// 打開網絡連接

//發送請求並獲取相應回應數據
HttpWebResponse response = myRequest.GetResponse() as HttpWebResponse;
//直到request.GetResponse()程序才開始向目標網頁發送Post請求 向服務器請求,獲得服務器的回應數據流
Stream readStream = response.GetResponseStream();
readStream.Flush();

HttpContext curContext = HttpContext.Current;
curContext.Response.ContentType = "application/pdf";//設置類型
curContext.Response.ContentEncoding = System.Text.Encoding.UTF8;
curContext.Response.Charset = "";
curContext.Response.AppendHeader("Content-Disposition", "attachment;filename=" + HttpUtility.UrlEncode(filename + "." + _filename[_filename.Length - 1], System.Text.Encoding.UTF8));

curContext.Response.AddHeader("Content-Length", remoteFileLength.ToString());
byte[] btArray = new byte[512];//一次最多讀取不能超過1024  此處設512
byte[] _btArrary = new byte[remoteFileLength + 512];//防止溢出
int currPostion = 0;
int contentSize = readStream.Read(btArray, 0, btArray.Length);// 向遠程文件讀第一次
while (contentSize > 0)// 如果讀取長度大於零則繼續讀
{
btArray.CopyTo(_btArrary, currPostion);
currPostion += contentSize;
contentSize = readStream.Read(btArray, 0, btArray.Length);// 繼續向遠程文件讀取
}

curContext.Response.BinaryWrite(_btArrary);
curContext.Response.End();
readStream.Close();

 

// 從文件頭得到遠程文件的長度

private static long GetHttpLength(string url)

{
long length = 0;

try
{
HttpWebRequest req = (HttpWebRequest)HttpWebRequest.Create(url);// 打開網絡連接
HttpWebResponse rsp = (HttpWebResponse)req.GetResponse();

if (rsp.StatusCode == HttpStatusCode.OK)
{
length = rsp.ContentLength;// 從文件頭得到遠程文件的長度
}

rsp.Close();
return length;
}
catch (Exception e)
{
return length;
}

}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM