根據網址把圖片下載到服務器C#代碼
ASPX頁面代碼:
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="GetPictureByUrl.aspx.cs" Inherits="HoverTreeMobile.GetPictureByUrl" %> <!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server"> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/> <meta name="viewport" content="width=device-width, initial-scale=1" /> <title>根據網址把圖片下載到服務器 - 何問起</title> </head> <body> <form id="form1" runat="server"> <div> 圖片網址:<br /><asp:TextBox runat="server" ID="textBoxImgUrl" Width="500" Text="http://hovertree.com/hvtimg/201508/cnvkv745.jpg" /> <br /> <asp:Button runat="server" ID="btnImg" Text="下載" OnClick="btnImg_Click" /> <br /><asp:Image runat="server" ID="hvtImg" /> <br /> <asp:Literal runat="server" ID="ltlTips" /> </div> </form> </body> </html>
猜謎語:
http://m.hovertree.com/miyu/bjae/4gwevb53.htm
cs頁面代碼:
using System; namespace HoverTreeMobile { public partial class GetPictureByUrl : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { } protected void btnImg_Click(object sender, EventArgs e) { try { System.Net.WebClient m_hvtWebClient = new System.Net.WebClient(); //如果不是指定格式圖片 //例如http://hovertree.com/hvtart/bjae/t2lo8pf7.htm 是htm文件,不是圖片 if (!(textBoxImgUrl.Text.EndsWith(".jpg") || textBoxImgUrl.Text.EndsWith(".gif") || textBoxImgUrl.Text.EndsWith(".png"))) { ltlTips.Text = "輸入的不是指定格式的圖片的網址"; return; } //生成隨機的圖片文件名 string m_picFileName = HoverTree.HoverTreeFrame.Utils.GetHoverTreeString()+ HoverTree.HoverTreeFrame.HoverString.GetLastStr(textBoxImgUrl.Text,4); string m_keleyiPicture = Server.MapPath("/hovertreeimages/"+ m_picFileName); //根據網址下載文件 m_hvtWebClient.DownloadFile(textBoxImgUrl.Text, m_keleyiPicture); hvtImg.ImageUrl = "/hovertreeimages/" + m_picFileName; ltlTips.Text = string.Empty; } catch(Exception ex) { ltlTips.Text = ex.ToString(); } } } }
//生成隨機的圖片文件名 string m_picFileName = HoverTree.HoverTreeFrame.Utils.GetHoverTreeString()+ HoverTree.HoverTreeFrame.HoverString.GetLastStr(textBoxImgUrl.Text,4);
以上代碼,請下載源代碼查看詳細實現方法。部分可到 http://hovertree.com/hvtart/bjae/tlhx2yn2.htm 查看
HoverTree 開源項目
新增根據網址把圖片下載到服務器功能
請看 HoverTreeMobile 項目
http://hovertree.com
何問起
源代碼下載 http://hovertree.com/down/