【问题标题】:Download and save image from HTML source从 HTML 源下载并保存图像
【发布时间】:2017-12-02 03:49:29
【问题描述】:

在我们的应用程序中,基于一些输入数据,将呈现图像。图片是一些图表。作为我们测试自动化的一部分,我需要下载这些图表。

我只有图片来源网址。如何从源下载图像并将其保存到磁盘。

我尝试使用不同的方法并能够下载文件。但是当我尝试打开文件时,收到一条消息说“不是有效的位图文件,或者它的格式目前不受支持。”

这是我的html

<div id="chart">
    <img id="c_12" src="Bonus/ModelChartImage?keys%5B0%5D=UKIrelandEBIT&values%5B0%5D=100&privacyModeServer=False&modelId=Bonus" alt="" usemap="#c_12ImageMap" style="height:300px;width:450px;border-width:0px;" />
<map name="c_12ImageMap" id="c_12ImageMap">

    <area shape="rect" coords="255,265,357,266" class="area-map-section" share="Core Bonus" alt="" />
    <area shape="rect" coords="128,43,229,265" class="area-map-section" share="Core Bonus" alt="" />
</map>    
</div> 

【问题讨论】:

标签: c# asp.net


【解决方案1】:

找到了答案。我们必须将网站上的 cookie 容器设置为您的请求。

public static Stream DownloadImageData(CookieContainer cookies, string siteURL)
{
    HttpWebRequest httpRequest = null;
    HttpWebResponse httpResponse = null;

    httpRequest = (HttpWebRequest)WebRequest.Create(siteURL);

    httpRequest.CookieContainer = cookies;
    httpRequest.AllowAutoRedirect = true;

    try
    {
        httpResponse = (HttpWebResponse)httpRequest.GetResponse();
        if (httpResponse.StatusCode == HttpStatusCode.OK)
        {
            var httpContentData = httpResponse.GetResponseStream();

            return httpContentData;
        }
        return null;
    }
    catch (WebException we)
    {
        return null;
    }
    finally
    {
        if (httpResponse != null)
        {
            httpResponse.Close();
        }
    }
}

【讨论】:

    【解决方案2】:

    从网站下载图片的方法有很多种(WebClient 类、HttpWebRequest、HttpClient 类,顺便说一句,其中新的HttpClient 是最简单的方法)。

    这是类 HttpClient 的示例:

    HttpClient httpClient = new HttpClient();
    Task<Stream> streamAsync = httpClient.GetStreamAsync("http://www.simedarby.com.au/images/SD.Corp.3D.4C.Pos.jpg");
    
    Stream result = streamAsync.Result;
    using (Stream fileStream = File.Create("downloaded.jpg"))
    {
        result.CopyTo(fileStream);
    }
    

    【讨论】:

    • 我尝试使用不同的方法并能够下载文件。但是当我尝试打开文件时,收到一条消息说“不是一个有效的位图文件,或者它的格式目前不受支持。”
    • 检查您是否实际下载了图像。可能是错误的扩展名,或者不是文件 HTML 中的图像,或者因为二进制文件中的“错误”添加了一些小字符串。所以首先检查下载的文件。
    • 网站正在开发基于表单的身份验证。在这种情况下,如果我尝试从另一个应用程序下载文件,我怎样才能将我的请求作为经过身份验证的请求。
    • Watin 好像死了。
    猜你喜欢
    • 1970-01-01
    • 2020-05-25
    • 1970-01-01
    • 2013-05-11
    • 2015-04-19
    • 2022-10-20
    • 1970-01-01
    • 2016-03-18
    • 2015-05-23
    相关资源
    最近更新 更多