类别:程序开发
日期:2022-08-12 浏览:2336 评论:0
C# 根据路径(URL)下载图片,保存对应路径,方便进一步的访问
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Net; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; namespace WebApplication { public partial class PICTURE : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { if (Request.QueryString["url"] != null) { //upload/2020/03/202003081583644238196529.png string url = Request.QueryString["url"].ToString(); string savePath = Server.MapPath("~/" + url); if (File.Exists(savePath)) { //存在 Response.Redirect("http://localhost:2064/upload/2020/03/202003081583644238196529.png"); } else { string fielpath = savePath.Substring(0, savePath.LastIndexOf('\\')); string fileName = savePath.Substring(savePath.LastIndexOf("\\", savePath.Length - 1)); if (!System.IO.Directory.Exists(fielpath)) { System.IO.Directory.CreateDirectory(fielpath);//不存在就创建文件夹 } bool i = DownloadPicture("https://vtzw.com/zb_users/upload/2020/03/202003081583644238196529.png", fielpath + fileName, -1); if (i) { Response.Redirect("http://localhost:2064/upload/2020/03/202003081583644238196529.png"); } } } } /// <summary> /// 下载图片 /// </summary> /// <param name="picUrl">图片Http地址</param> /// <param name="savePath">保存路径</param> /// <param name="timeOut">Request最大请求时间,如果为-1则无限制</param> /// <returns></returns> public bool DownloadPicture(string picUrl, string savePath, int timeOut) { 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); } 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; } } }
本文标题:C# 根据路径(URL)下载图片,保存对应路径
本文链接:https://vtzw.com/post/1032.html
版权声明:本文不使用任何协议授权,您可以任何形式自由转载或使用。
发表评论 / 取消回复