Saturday, 3 August 2013

Save Image from External Link

Aspx Page
========
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="ExternalLinkToImageSave.aspx.cs" Inherits="ExternalLinkToImageSave" %>

<!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 id="Head1" runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:TextBox runat="server" ID="txtUpload" />
                    <asp:Button runat="server" ID="btnUpload" OnClick="Upload" Text="Upload" />
    </div>
    </form>
</body>
</html>

.Cs Page
=======
   protected void Upload(object sender, EventArgs e)
    {
        HttpWebRequest request = (System.Net.HttpWebRequest)WebRequest.Create(this.txtUpload.Text);
        HttpWebResponse response = request.GetResponse() as HttpWebResponse;
        Stream stream = response.GetResponseStream();
        string ext = response.ContentType;
        string[] strArray = ext.Split('/');
        ext = strArray[1];
        ///
        /// use response content type to findout the image type,
        /// here I just use jpg to simplify the story.
        ///
        System.Drawing.Image image = System.Drawing.Image.FromStream(stream);
        //image.Save(this.Server.MapPath(string.Format("~/Uploads/{0}.jpg", Guid.NewGuid())));
        image.Save(this.Server.MapPath(string.Format("~/Uploads/{0}."+ext+"", Guid.NewGuid())));
    }

No comments:

Post a Comment