图片网址具有的contentType" text / html的" [英] Image URL has the contentType "text/html"

查看:739
本文介绍了图片网址具有的contentType" text / html的"的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我要实现从网站上下载图片到电脑的方法。

I want to implement a method to download Image from website to laptop.

public static void DownloadRemoteImageFile(string uri, string fileName)
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uri);
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
if ((response.StatusCode == HttpStatusCode.OK ||
            response.StatusCode == HttpStatusCode.Moved ||
            response.StatusCode == HttpStatusCode.Redirect) &&
            response.ContentType.StartsWith("image", StringComparison.OrdinalIgnoreCase))
        {
             //if the remote file was found, download it
            using (Stream inputStream = response.GetResponseStream())
            using (Stream outputStream = File.OpenWrite(fileName))
            {
                byte[] buffer = new byte[4096];
                int bytesRead;
                do
                {
                    bytesRead = inputStream.Read(buffer, 0, buffer.Length);
                    outputStream.Write(buffer, 0, bytesRead);
                } while (bytesRead != 0);
            }
        }
}



的ContentType 要求或响应不是图像/ JPG或图像> / PNG。他们总是text / html的。我想这就是为什么当我将其保存到本地,他们有不正确的内容,我无法查看。

But the ContentType of request or response is not "image/jpg" or "image/png". They're always "text/html". I think that's why after I save them to local, they has incorrect content and I cannot view them.

任何人都可以有一个解决方案吗?
谢谢

Can anyone has a solution here? Thanks

推荐答案

这是可能的,该网站希望从可能需要获得图像(S)的饼干(S)的。有时,当我们用我们的浏览器去到现场,我们可能没有注意到它,但浏览器实际去现场为也许是毫秒,迅速重装前,而在同一时间让该cookie。但同样加载该网站之前,我们的浏览器将其传递cookie的这个时候,即网站的接受它,并返回图像。

It may be possible that the sites you wish to get the image(s) from may need a cookie(s). Sometimes when we use our browsers to go to the site, we may not notice it, but the browser actually goes to the site for perhaps a millisecond, before quickly reloading, while at the same time getting the cookie. But before loading the site again, our browser would then pass it the cookie this time, whereby the site accepts it and returns the image.

为了详细说明,这意味着你的方法会做只是你的浏览器实际上做的一半。 2 GET请求方法的一半。 。第一个是得到的cookie,而第二个真正得到图像本身

To elaborate, this means your method would be doing only half of what your browser is actually doing. Half of 2 GET request methods. The first one would be to get the cookie, and the second one to actually get the image itself.

这(也许有点相关)信息:的C#生成一个cookie动态该网站会接受吗?

Information from (and maybe a bit related): C# generate a cookie dynamically that site will accept?

这篇关于图片网址具有的contentType" text / html的"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆