C# 远程图片下载到本地
下载方法
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 | using System; using System.Net; using System.IO; using System.Text; namespace Common { /// <summary> /// 下载远程图片保存到本地地址 /// </summary> public class DowloadWXImg { /// <summary> /// 下载图片 /// </summary> /// <param name="picUrl">图片Http地址</param> /// <param name="savePath">保存路径</param> /// <param name="timeOut">Request最大请求时间,如果为-1则无限制</param> /// <returns></returns> public static bool DownloadPicture( string picUrl, string savePath, int timeOut=-1) { bool value = false ; WebResponse response = null ; Stream stream = null ; try { HttpWebRequest request = (HttpWebRequest)WebRequest.Create(picUrl); if (timeOut != -1) request.Timeout = timeOut; response = request.GetResponse(); stream = response.GetResponseStream(); if (!response.ContentType.ToLower().StartsWith( "text/" )) value = SaveBinaryFile(response, savePath); } catch (Exception e) { LogHelper.AddErrorLog( "下载远程图片失败:" +e.ToString()); } finally { if (stream != null ) stream.Close(); if (response != null ) response.Close(); } return value; } private static bool SaveBinaryFile(WebResponse response, string savePath) { bool value = false ; byte [] buffer = new byte [1024]; Stream outStream = null ; Stream inStream = null ; try { if (File.Exists(savePath)) File.Delete(savePath); outStream = System.IO.File.Create(savePath); inStream = response.GetResponseStream(); int l; do { l = inStream.Read(buffer, 0, buffer.Length); if (l > 0) outStream.Write(buffer, 0, l); } while (l > 0); value = true ; } finally { if (outStream != null ) outStream.Close(); if (inStream != null ) inStream.Close(); } return value; } } } |
流程:
string img = "/Img/CustomerHeadImg/" + OrgID; //string SavaWxImage = Server.MapPath(img); //该方法是获取网站所在的根目录
//
//System.AppDomain.CurrentDomain.BaseDirectory 这个方法 是获取网站下面的应用程序目录
string SavaWxImage = System.AppDomain.CurrentDomain.BaseDirectory+img; if (!Directory.Exists(SavaWxImage))//是否存在文件夹,没存在则创建 Directory.CreateDirectory(SavaWxImage); bool isWXImg = DowloadWXImg.DownloadPicture(wxImage, SavaWxImage+"/" + unionid + ".jpg");
本文来自博客园,作者:12不懂3,转载请注明原文链接:https://www.cnblogs.com/LZXX/p/7840307.html
标签:
c#远程下载图片到本地
, c#远程下载图片到应用程序下面
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
· 一个奇形怪状的面试题:Bean中的CHM要不要加volatile?
· 分享4款.NET开源、免费、实用的商城系统
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
· 上周热点回顾(2.24-3.2)
2016-11-15 单元测试-NUint最基本使用详解