C#下载http/https的pdf、excel等文件(非在线打开,绕开插件)

2021-06-23 11:06

阅读:589

标签:类型   string   文件的   后缀   excel   contents   contex   res   导出   

非本服务器文件,如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", "");

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;
}

}

C#下载http/https的pdf、excel等文件(非在线打开,绕开插件)

标签:类型   string   文件的   后缀   excel   contents   contex   res   导出   

原文地址:https://www.cnblogs.com/zhuangjolon/p/10195663.html


评论


亲,登录后才可以留言!