zoukankan      html  css  js  c++  java
  • (转)远程下载图片

    转自:http://stackoverflow.com/questions/3615800/download-image-from-the-site-in-net-c

    方法1:

    string localFilename = @"c:localpath	ofile.jpg";
    using(WebClient client = new WebClient())
    {
        client.DownloadFile("http://www.example.com/image.jpg", localFilename);
    }

    方法2:

    private static void DownloadRemoteImageFile(string uri, string fileName)
    {
        HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uri);
        HttpWebResponse response = (HttpWebResponse)request.GetResponse();
    
        // Check that the remote file was found. The ContentType
        // check is performed since a request for a non-existent
        // image file might be redirected to a 404-page, which would
        // yield the StatusCode "OK", even though the image was not
        // found.
        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 oit
            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);
            }
        }
    }
  • 相关阅读:
    I/O流
    课堂测试
    1021课堂内容
    课堂jsp
    课堂动手动脑
    从小工到专家读后感
    课堂测试2
    回文课堂测试
    一周进度条博客
    Echart图表
  • 原文地址:https://www.cnblogs.com/jiajinyi/p/4088411.html
Copyright © 2011-2022 走看看