.net 直接输出远程文件到浏览器和下载文件保存到本机

时间:2022-04-14 08:44:16

利用了xmlhttp,实现代码比较简单具体实现如下:

首先bin文件引入,com->microsoft xml v3.0

具体代码如下:

protected void Button1_Click(object sender, EventArgs e)
{
string FileNames = "201406251824392435.pdf", ContentType = "";
string houzhui = FileNames.Substring(FileNames.LastIndexOf("."));
ContentType = checktype(FileNames);
string Url = "http://xxx.xxx.xxx.xxx:8089/upfile/wenku/" + FileNames;//域名或者ip地址
string StringFileName = Url.Substring(Url.LastIndexOf("/") + );
string StringFilePath = Request.PhysicalApplicationPath;
if (!StringFilePath.EndsWith("/")) StringFilePath += "/";
try
{
MSXML2.XMLHTTP _xmlhttp = new MSXML2.XMLHTTPClass();
_xmlhttp.open("GET", Url, false, null, null);
_xmlhttp.send("");
if (_xmlhttp.readyState == )//数据接收完毕
{
if (_xmlhttp.status == )//是否返回正确数据
{
HttpContext.Current.Response.AddHeader("Content-Disposition", "attachment; filename=" + HttpUtility.UrlEncode("测试" + houzhui, System.Text.Encoding.UTF8));
HttpContext.Current.Response.ContentType = ContentType;
HttpContext.Current.Response.BinaryWrite((byte[])_xmlhttp.responseBody);//输出二进制到浏览器
HttpContext.Current.Response.Flush();
HttpContext.Current.Response.End();
}
else
{ Response.Write("错误:" + _xmlhttp.statusText + " 未找到要下载的文件!"); }
}
else
{
Response.Write("错误:" + _xmlhttp.statusText + " 请求的http地址不对!");
Response.End();
}
}
catch (Exception ex)
{
Response.Write("错误:无法找到请求的资源!");
Response.End();
} }

返回mime类型:

private static string checktype(string filename)
{
string ContentType;
string houzhui = filename.Substring(filename.LastIndexOf(".") + ).Trim().ToLower();
switch (houzhui)
{
case ".asf":
ContentType = "video/x-ms-asf ";
break;
case ".avi":
ContentType = "video/avi ";
break;
case ".doc":
ContentType = "application/msword ";
break;
case ".zip":
ContentType = "application/zip ";
break;
case ".xls":
ContentType = "application/vnd.ms-excel ";
break;
case ".gif":
ContentType = "image/gif ";
break;
case ".jpg":
ContentType = "image/jpeg ";
break;
case "jpeg":
ContentType = "image/jpeg ";
break;
case ".wav":
ContentType = "audio/wav ";
break;
case ".mp3":
ContentType = "audio/mpeg3 ";
break;
case ".mpg":
ContentType = "video/mpeg ";
break;
case ".mepg":
ContentType = "video/mpeg ";
break;
case ".rtf":
ContentType = "application/rtf ";
break;
case ".html":
ContentType = "text/html ";
break;
case ".htm":
ContentType = "text/html ";
break;
case ".txt":
ContentType = "text/plain ";
break;
case ".pdf":
ContentType = "application/pdf";
break;
default:
ContentType = "application/octet-stream ";
break;
}
return ContentType;
}

下载文件并保存到本机:

 /// <summary>
/// 获取远程文件到本地
/// </summary>
/// <param name="url">远程文件地址</param>
/// <param name="path">本地路径</param>
private static void DownUrltoFile(string url, string path)
{
string Cookie = String.Empty;
String refer = url.Substring(0, url.LastIndexOf("/") + 1);
System.Net.HttpWebRequest req = System.Net.HttpWebRequest.Create(url) as System.Net.HttpWebRequest;
req.AllowAutoRedirect = false;
req.Referer = refer;
req.UserAgent = "Mozilla/5.0 (Windows; U; Windows NT 6.1; zh-CN; rv:1.9.2.13) Gecko/20101203 Firefox/3.6.13";
System.Net.HttpWebResponse res = req.GetResponse() as System.Net.HttpWebResponse;
System.Net.WebHeaderCollection headers = res.Headers;
String newUrl = "";
if ((res.StatusCode == System.Net.HttpStatusCode.Found) ||
(res.StatusCode == System.Net.HttpStatusCode.Redirect) ||
(res.StatusCode == System.Net.HttpStatusCode.Moved) ||
(res.StatusCode == System.Net.HttpStatusCode.MovedPermanently))
{
newUrl = headers["Location"];
newUrl = newUrl.Trim();
} if (headers["Set-Cookie"] != null)
{
Cookie = headers["Set-Cookie"];
}
res.Close();
req = null;
String fileName = newUrl.Substring(newUrl.LastIndexOf("/") + 1);
req = System.Net.HttpWebRequest.Create(url) as System.Net.HttpWebRequest;
req.AllowAutoRedirect = true;
req.Referer = url;
req.UserAgent = "Mozilla/5.0 (Windows; U; Windows NT 6.1; zh-CN; rv:1.9.2.13) Gecko/20101203 Firefox/3.6.13";
res = req.GetResponse() as System.Net.HttpWebResponse;
System.IO.Stream stream = res.GetResponseStream();
byte[] buffer = new byte[32 * 1024];
int bytesProcessed = 0;
System.IO.FileStream fs = System.IO.File.Create(HttpContext.Current.Server.MapPath(path));
int bytesRead;
do
{
bytesRead = stream.Read(buffer, 0, buffer.Length);
fs.Write(buffer, 0, bytesRead);
bytesProcessed += bytesRead;
}
while (bytesRead > 0);
fs.Flush();
fs.Close();
res.Close();
}

  

HttpWebRequest,下载远程文件输出到浏览器

    调用:ReadFileWriterBinary("http://1.1.1.1:8889/xxx/xxx/xxx.pdf", "xx.pdf");

    private void ReadFileWriterBinary(String path, String fileName)
{
HttpWebRequest myWebRequest = (HttpWebRequest)WebRequest.Create(path);
HttpWebResponse myWebResponse = (HttpWebResponse)myWebRequest.GetResponse();
Stream readStream = myWebResponse.GetResponseStream();
BinaryReader SplitFileReader = new BinaryReader(readStream);
HttpContext.Current.Response.ContentType = "application/save";
HttpContext.Current.Response.AddHeader("Content-Disposition", "attachment; filename=" + HttpUtility.UrlEncode(fileName, System.Text.Encoding.UTF8));
byte[] TempBytes = SplitFileReader.ReadBytes(Convert.ToInt32(myWebResponse.ContentLength));
HttpContext.Current.Response.BinaryWrite(TempBytes);
SplitFileReader.Close();
readStream.Close();
}

  

完善后,注释掉的是本地的处理:

/// <summary>
/// 下载文件
/// </summary>
/// <param name="URL">下载文件地址</param>
/// <param name="Filename">下载后的存放地址</param>
public string DownloadFile(string URL, string filename)
{
try
{
System.Net.HttpWebRequest Myrq = (System.Net.HttpWebRequest)
System.Net.HttpWebRequest.Create(URL);
System.Net.HttpWebResponse myrp = (System.Net.HttpWebResponse)Myrq.GetResponse();
long totalBytes = myrp.ContentLength;
if (myrp.ContentLength != )
{
System.IO.Stream st = myrp.GetResponseStream();
//System.IO.Stream so = new System.IO.FileStream(filename,System.IO.FileMode.Create); Response.Clear();
long totalDownloadedByte = ;
byte[] by = new byte[];
int osize = st.Read(by, , (int)by.Length);
Response.ContentType = "application/octet-stream";
Response.AddHeader("Content-Disposition", "attachment; filename=" + HttpUtility.UrlEncode(filename));
while (osize > )
{
totalDownloadedByte = osize + totalDownloadedByte;
Response.OutputStream.Write(by, , osize);
Response.Flush();
//so.Write(by, 0, osize);
osize = st.Read(by, , (int)by.Length);
}
Response.Close(); //long totalDownloadedByte = 0;
//byte[] by = new byte[1024];
//int osize = st.Read(by, 0, (int)by.Length);
//while (osize > 0)
//{
// totalDownloadedByte = osize + totalDownloadedByte;
// so.Write(by, 0, osize);
// osize = st.Read(by, 0, (int)by.Length);
//}
//so.Close();
st.Close();
return "success";
}
else
{
return "文件不存在";
}
}
catch (System.Exception e)
{
return "下载文件失败!" + e.ToString();
}
}