非本服務(wù)器文件,如PDF,excel等,下載一般是通過href=‘遠(yuǎn)程文件的http或者h(yuǎn)ttps’的方式下載,但是如果瀏覽器已經(jīng)有PDF插件了,則用href不是下載,而是在線打開了,影響體驗(yàn),所以遠(yuǎn)程服務(wù)器文件下載改為后臺(tái)的方式下載,可以繞開插件。代碼如下:
string url = hidFilePath.Value;//文件的地址:如http://emec.h.c/pdf/test.pdf
string filename = hidFileName.Value;//導(dǎo)出的文件名稱:如測(cè)試導(dǎo)出文件
//處理后綴
string[] _filename = url.Split(''.'');//得到文件后綴
long remoteFileLength = GetHttpLength(url);// 取得遠(yuǎn)程文件長(zhǎng)度
if (remoteFileLength == 745 || remoteFileLength == 0)
{
Page.ClientScript.RegisterClientScriptBlock(GetType(), "js", "<script>alert(''遠(yuǎn)程文件不存在'');</script>");
return;
}
HttpWebRequest myRequest = (HttpWebRequest)HttpWebRequest.Create(url);// 打開網(wǎng)絡(luò)連接
//發(fā)送請(qǐng)求并獲取相應(yīng)回應(yīng)數(shù)據(jù)
HttpWebResponse response = myRequest.GetResponse() as HttpWebResponse;
//直到request.GetResponse()程序才開始向目標(biāo)網(wǎng)頁(yè)發(fā)送Post請(qǐng)求 向服務(wù)器請(qǐng)求,獲得服務(wù)器的回應(yīng)數(shù)據(jù)流
Stream readStream = response.GetResponseStream();
readStream.Flush();
HttpContext curContext = HttpContext.Current;
curContext.Response.ContentType = "application/pdf";//設(shè)置類型
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 此處設(shè)512
byte[] _btArrary = new byte[remoteFileLength + 512];//防止溢出
int currPostion = 0;
int contentSize = readStream.Read(btArray, 0, btArray.Length);// 向遠(yuǎn)程文件讀第一次
while (contentSize > 0)// 如果讀取長(zhǎng)度大于零則繼續(xù)讀
{
btArray.CopyTo(_btArrary, currPostion);
currPostion += contentSize;
contentSize = readStream.Read(btArray, 0, btArray.Length);// 繼續(xù)向遠(yuǎn)程文件讀取
}
curContext.Response.BinaryWrite(_btArrary);
curContext.Response.End();
readStream.Close();
// 從文件頭得到遠(yuǎn)程文件的長(zhǎng)度
private static long GetHttpLength(string url)
{
long length = 0;
try
{
HttpWebRequest req = (HttpWebRequest)HttpWebRequest.Create(url);// 打開網(wǎng)絡(luò)連接
HttpWebResponse rsp = (HttpWebResponse)req.GetResponse();
if (rsp.StatusCode == HttpStatusCode.OK)
{
length = rsp.ContentLength;// 從文件頭得到遠(yuǎn)程文件的長(zhǎng)度
}
rsp.Close();
return length;
}
catch (Exception e)
{
return length;
}
}
該文章在 2021/1/29 8:40:58 編輯過