WebClient 從網上下載圖片

來源:互聯網
上載者:User

測試了很多次,在網上也找了不少的資料,卻沒有找到一個自己想要的,比如該設定檔,加上heads.add標頭檔都試過,但是還是沒有實現目的,都是報錯。最後終於還是找到了一個很簡單的實現方法:

1、首先下載msxml2.dll

2、用戶端代碼

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="MsXmlTest.aspx.cs" Inherits="MyWeb.MsXmlTest" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
    <title></title>
    <style type="text/css">
        #txt1
        {
            width: 466px;
            height: 51px;
        }
        #txt2
        {
            width: 464px;
            height: 51px;
        }
    </style>
</head>
<body>
    <form id="form1" runat="server">
    <div>
    <input type="text" id="txt1" runat="server"/><br />
    <input type="text" id="txt2" runat="server" /><br />
    <asp:Button ID="btn" runat="server" Text="MsXml測試" onclick="btn_Click" />
    </div>
    </form>
</body>
</html>

2、實現方法

/// <summary>
        /// 下載指定url路徑的檔案
        /// </summary>
        /// <param name="url">指定url路徑</param>
        /// <param name="filename">需要儲存的路徑</param>
        /// <param name="type">請求方式(GET或POST)</param>
        private void Down(string url, string filename, string type)
        {
            XMLHTTP xmlhttp = new XMLHTTPClass();
            xmlhttp.open(type, url, false, null, null);
            xmlhttp.send("");
            if (xmlhttp.readyState == 4)
            {
                if (xmlhttp.status == 200)
                {
                    byte[] mybyte = (byte[])xmlhttp.responseBody;
                    FileStream fs = new FileStream(filename, FileMode.Create, FileAccess.Write);
                    fs.Write(mybyte, 0, mybyte.Length);
                    fs.Close();
                }
            }
        }

3、調用

protected void btn_Click(object sender, EventArgs e)
        {
            //Down("http://list.image.baidu.com/t/image_category/galleryimg/wallpaper/human/han_gmn.jpg", "E://b.jpg", "GET");
            Down(this.txt1.Value, this.txt2.Value, "GET");
        }

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.