| 在.NET中利用XMLHTTP下载文件 |
作者:孟宪会 发布日期:2004-09-02 18:34:11
|
利用XMLHTTP下载文件,和以前的方法一样,先添加引用-COM-Microsoft Xml 3.0,并且在服务器上使用时要把 Interop.MSXML2.dll 也放在Bin下。然后在代码开始处写:
下面就是主要的代码:
ASPX 代码
<%@ Page Language="C#" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<script runat="server">
protected void Button1_Click(object sender, EventArgs e)
{
string Url = TextBox1.Text;
string StringFileName = Url.Substring(Url.LastIndexOf("/") + 1);
string StringFilePath = Request.PhysicalApplicationPath;
if (!StringFilePath.EndsWith("/")) StringFilePath += "/";
MSXML2.XMLHTTP _xmlhttp = new MSXML2.XMLHTTPClass();
_xmlhttp.open("GET", Url, false, null, null);
_xmlhttp.send("");
if (_xmlhttp.readyState == 4)
{
if (System.IO.File.Exists(StringFilePath + StringFileName))
System.IO.File.Delete(StringFilePath + StringFileName);
System.IO.FileStream fs = new System.IO.FileStream(StringFilePath + StringFileName, System.IO.FileMode.CreateNew);
System.IO.BinaryWriter w = new System.IO.BinaryWriter(fs);
w.Write((byte[])_xmlhttp.responseBody);
w.Close();
fs.Close();
Response.Write("文件已经得到。<br><a href='" + VirtualPathUtility.ToAbsolute("~/") + StringFileName + "' target='_blank'>");
Response.Write("查看" + StringFileName + "</a>");
}
else
{
Response.Write(_xmlhttp.statusText);
}
Response.End();
}
</script>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">请输入一个图片地址:<br />
<asp:TextBox ID="TextBox1" runat="server"
Text="http://dotnet.aspx.cc/Images/logoSite.gif" Width="822px"></asp:TextBox>
<br />
<br />
<asp:Button ID="Button1" runat="server" Text="获取图片" onclick="Button1_Click" />
</form>
</body>
</html>
|
原文地址:http://dotnet.aspx.cc/article/4ae836f8-ccb4-4bef-90b1-25bb1a5e6433/print.aspx
© 版权所有 【孟宪会之精彩世界】TM 2012