HttpWebRequest实现下载图片至本地

本文为大家分享了HttpWebRequest实现下载图片至本地的具体代码,供大家参考,具体内容如下

HttpWebRequest发送web请求,获取流文件,保存至本地

using System;
using System.IO;
using System.Net;
using System.Text;
using System.Web.Mvc;

namespace Web.Controllers
{
  public class HomeController : Controller
  {
    string url = "http://www.***.com/Image.aspx?ucode=ucode";

    public Stream GetFileToStream(string filePath)
    {
      FileStream fileStream = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.Read);
      byte[] bytes = new byte[fileStream.Length];
      fileStream.Read(bytes, 0, bytes.Length);
      fileStream.Close();
      Stream streamFile = new MemoryStream(bytes);
      return streamFile;
    }

    public void Method1()
    {
      string fileName = @"\upload\" + GenerateTimeStamp() + ".jpg";

      string webPath = Server.MapPath(fileName);
      string pathName = @"d:\" + GenerateTimeStamp() + ".jpg";
      HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);

      req.ServicePoint.Expect100Continue = false;
      req.Method = "GET";
      req.KeepAlive = true;

      req.ContentType = "image/png";
      HttpWebResponse rsp = (HttpWebResponse)req.GetResponse();

      System.IO.Stream stream = null;

      try
      {
        //以字符流的方式读取HTTP响应
        stream = rsp.GetResponseStream();
        System.Drawing.Image.FromStream(stream).Save(pathName);
      }
      finally
      {
        // 释放资源
        if (stream != null) stream.Close();
        if (rsp != null) rsp.Close();
      }
    }

    protected void Method2()
    {
      string fileName = @"\upload\" + GenerateTimeStamp() + ".jpg";

      string webPath = Server.MapPath(fileName);
      string pathName = @"d:\" + GenerateTimeStamp() + ".jpg";
      HttpWebRequest myRequest = (HttpWebRequest)WebRequest.Create(url);
      myRequest.Method = "GET";

      HttpWebResponse myResponse = null;
      try
      {
        myResponse = (HttpWebResponse)myRequest.GetResponse();
        StreamReader reader = new StreamReader(myResponse.GetResponseStream(), Encoding.UTF8);
        Stream stream = myResponse.GetResponseStream();

        #region 保存下载图片

        MemoryStream ms = null;
        Byte[] buffer = new Byte[myResponse.ContentLength];
        int offset = 0, actuallyRead = 0;
        do
        {
          actuallyRead = stream.Read(buffer, offset, buffer.Length - offset);
          offset += actuallyRead;
        }
        while (actuallyRead > 0);
        ms = new MemoryStream(buffer);

        byte[] buffurPic = ms.ToArray();
        System.IO.File.WriteAllBytes(pathName, buffurPic);

        #endregion
      }
      //异常请求
      catch (WebException ex)
      {

      }
    }

    protected void Method3()
    {
      string fileName = @"\upload\" + GenerateTimeStamp() + ".jpg";

      string webPath = Server.MapPath(fileName);
      string pathName = @"d:\" + GenerateTimeStamp() + ".jpg";
      HttpWebRequest myRequest = (HttpWebRequest)WebRequest.Create(url);
      myRequest.Method = "GET";

      HttpWebResponse myResponse = null;
      try
      {
        myResponse = (HttpWebResponse)myRequest.GetResponse();
        StreamReader reader = new StreamReader(myResponse.GetResponseStream(), Encoding.UTF8);
        Stream stream = myResponse.GetResponseStream();

        #region 保存下载图片

        FileStream fileStream = new FileStream(pathName, FileMode.Create, FileAccess.Write);
        byte[] bytes = new byte[1024];
        int readSize = 0;
        while ((readSize = stream.Read(bytes, 0, 1024)) > 0)
        {
          fileStream.Write(bytes, 0, readSize);
          fileStream.Flush();
        }
        #endregion

        myResponse.Close();
        stream.Close();
        fileStream.Close();
      }
      //异常请求
      catch (WebException ex)
      {

      }
      finally
      {

      }
    }

    public string GenerateTimeStamp()
    {
      TimeSpan ts = DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, 0);
      return Convert.ToInt64(ts.TotalMilliseconds).ToString();
    }
  }
}

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持我们。

(0)

相关推荐

  • C#实现把图片下载到服务器代码

    C#实现把图片下载到服务器代码 ASPX页面代码: <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="GetPictureByUrl.aspx.cs" Inherits="HoverTreeMobile.GetPictureByUrl" %> <!DOCTYPE html> <html xmlns="http://www.

  • Unity3D实现批量下载图片功能

    本文实例为大家分享了Unity3D实现批量下载图片功能的具体代码,供大家参考,具体内容如下 下一篇文章试试用线程下载 代码如下 using System.IO; using UnityEngine; using System.Net; using System.Collections; public class Test : MonoBehaviour { private string[] _urls=new string[10]; private string [] _localPath =

  • C#实现上传下载图片

    本文实例为大家分享了C#实现上传下载图片的具体代码,供大家参考,具体内容如下 1.首先我们通过流来上传下载图片,所有操作只停留在流这一层 MemoryStream ms; //左侧按钮 private void button1_Click(object sender, EventArgs e) { ms = new MemoryStream(); Image bi =pictureBox1.Image; bi.Save(ms, pictureBox1.Image.RawFormat);//将图片

  • Asp.net(C#)读取数据库并生成JS文件制作首页图片切换效果(附demo源码下载)

    本文实例讲述了Asp.net(C#)读取数据库并生成JS文件制作首页图片切换效果的方法.分享给大家供大家参考,具体如下: using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using System.Text; using System.IO; public partial

  • HttpWebRequest实现下载图片至本地

    本文为大家分享了HttpWebRequest实现下载图片至本地的具体代码,供大家参考,具体内容如下 HttpWebRequest发送web请求,获取流文件,保存至本地 using System; using System.IO; using System.Net; using System.Text; using System.Web.Mvc; namespace Web.Controllers { public class HomeController : Controller { strin

  • php正则匹配文章中的远程图片地址并下载图片至本地

    使用php的正则表达式来实现: $content = '这里是文章内容,这里插入一张图片测试 <img src="XXXXXXXXXXXXXXXXXXXX">'; $content = stripslashes ( $content ); $img_array = array (); // 匹配所有远程图片 preg_match_all ( "/(src|SRC)=["|'| ]{0,}(http://(.*).(gif|jpg|jpeg|bmp|png

  • java实现从网上下载图片到本地的方法

    本文实例讲述了java实现从网上下载图片到本地的方法.分享给大家供大家参考.具体如下: import java.io.*; import java.net.MalformedURLException; import java.net.URL; public static void writeFile(String strUrl,String fileName){ URL url = null; try { url = new URL(strUrl); } catch (MalformedURLE

  • php 替换文章中的图片路径,下载图片到本地服务器的方法

    php 替换文章中的图片路径,下载图片到本地服务器 /** * 获取替换文章中的图片路径 * @param string $xstr 内容 * @param string $oriweb 网址 * @return string * */ function replaceimg($xstr, $oriweb){ //保存路径 $d = date('Ymd', time()); $saveimgfile_1 = '/uploads/allimg/'.$d; $dirslsitss = DEDEROO

  • C#实现批量下载图片到本地示例代码

    一.概述 批量下载图片是我们在日常开发中经常会遇到的一个需求,这不,最近工作中就需要批量下载图片到本地,先是通过Excel拼接生成了所有链接地址,然后想到的是通过下载软件来批量下载.可是一想到又要花时间去查找.安装.研究软件,不如自己写个来的快. 以下是使用C#开发的控制台程序代码,通过循环读取文本文件中每一行地址字符串,执行下载并保存到本地文件夹中. 下面话不多说了,来一起看看详细的介绍吧 二.C#实例代码 //using System; //using System.Net; //using

  • PHP通过正则表达式下载图片到本地的实现代码

    复制代码 代码如下: <?php /* author: ssh_kobe date: 20110602 shortage: 如果网页中的图片路径不是绝对路径,就无法抓取 */ set_time_limit(0);//抓取不受时间限制 $URL='http://pp.baidu.com/';//任意网址 get_pic($URL); function get_pic($pic_url) { //获取图片二进制流 $data=CurlGet($pic_url); /*利用正则表达式得到图片链接*/

  • nodejs制作爬虫实现批量下载图片

    今天想获取一大批猫的图片,然后就在360流浪器搜索框中输入 猫 ,然后点击图片.就看到了一大波猫的图片: http://image.so.com/i?q=%E7%8... ,我在想啊,要是审查元素,一张张手动下载,多麻烦,所以打算写程序来实现.不写不知道,一写发现里面还是有很多道道的. 1. 爬取图片链接 因为之前也写过nodejs爬虫功能(参见:NodeJS制作爬虫全过程),所以觉得应该很简单,就用cheerio来处理dom啦,结果打印一下啥也没有,后来查看源代码: 发现 waterfall_

  • nodejs批量下载图片的实现方法

    今天想获取一大批猫的图片,然后就在360流浪器搜索框中输入猫,然后点击图片.就看到了一大波猫的图片:http://image.so.com/i?q=%E7%8...,我在想啊,要是审查元素,一张张手动下载,多麻烦,所以打算写程序来实现.不写不知道,一写发现里面还是有很多道道的. 1. 爬取图片链接 因为之前也写过nodejs爬虫功能,所以觉得应该很简单,就用cheerio来处理dom啦,结果打印一下啥也没有,后来查看源代码: 发现waterfall_zoom里面空空如也,查找了一下,发现所有的数

  • java多线程实现下载图片并压缩

    最近在做一个需求:从其他系统的ftp目录下载存储图片url的文件,然后读取文件中的url地址,根据地址下载图片后按天压缩成一个包,平均一个地址文件中包含4000个地址左右,也就是说一个文件扫描后需要下载4000个左右的图片,然后压缩,下面把我的实现方式和优化过程记录下来,如果大家有什么更好的方式可以分享. 使用框架:SpringMVC 定时任务实现:继承org.springframework.scheduling.quartz.QuartzJobBean; ftp环境搭建就不说了,在其他博客记录

  • Vue+mui实现图片的本地缓存示例代码

    下面一段代码给大家分享基于Vue+mui实现图片的本地缓存,具体代码如下所示: const menu = { state: { products: {}, GLOBAL_CONFIG:GLOBAL_CONFIG['GLOBAL_CONFIG'] }, mutations: { get_product: function (state, products) { //商品列表 state.products = products; for(let i = 0; i < state.products.l

随机推荐