非本服務(wù)器文件,如PDF,excel等,下載一般是通過href=‘遠程文件的http或者https’的方式下載,但是如果瀏覽器已經(jīng)有PDF插件了,則用href不是下載,而是在線打開了,影響體驗,所以遠程服務(wù)器文件下載改為后臺的方式下載,可以繞開插件。代碼如下:
string url = hidFilePath.Value;//文件的地址:如http://emec.h.c/pdf/test.pdf
string filename = hidFileName.Value;//導(dǎo)出的文件名稱:如測試導(dǎo)出文件
//處理后綴
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);// 打開網(wǎng)絡(luò)連接
//發(fā)送請求并獲取相應(yīng)回應(yīng)數(shù)據(jù)
HttpWebResponse response = myRequest.GetResponse() as HttpWebResponse;
//直到request.GetResponse()程序才開始向目標網(wǎng)頁發(fā)送Post請求 向服務(wù)器請求,獲得服務(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);// 向遠程文件讀第一次
while (contentSize > 0)// 如果讀取長度大于零則繼續(xù)讀
{
btArray.CopyTo(_btArrary, currPostion);
currPostion += contentSize;
contentSize = readStream.Read(btArray, 0, btArray.Length);// 繼續(xù)向遠程文件讀取
}
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);// 打開網(wǎng)絡(luò)連接
HttpWebResponse rsp = (HttpWebResponse)req.GetResponse();
if (rsp.StatusCode == HttpStatusCode.OK)
{
length = rsp.ContentLength;// 從文件頭得到遠程文件的長度
}
rsp.Close();
return length;
}
catch (Exception e)
{
return length;
}
}
該文章在 2021/1/29 8:40:58 編輯過