C#服務端圖片打包下載實現(xiàn)代碼解析
更新時間:2020年07月13日 14:50:45 作者:葉丶梓軒
這篇文章主要介紹了C#服務端圖片打包下載實現(xiàn)代碼解析,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友可以參考下
一,設計多圖片打包下載邏輯:
1,如果是要拉取騰訊云等資源服務器的圖片,
2,我們先把遠程圖片拉取到本地的臨時文件夾,
3,然后壓縮臨時文件夾,
4,壓縮完刪除臨時文件夾,
5,返回壓縮完給用戶,
6,用戶就去請求下載接口,當下載完后,刪除壓縮包
二,如下代碼,ImageUtil
using System;
using System.Collections.Generic;
using System.IO;
using System.IO.Compression;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Web;
namespace Common
{
/// <summary>
/// 要引用
/// System.IO.Compression.FileSystem
/// System.IO.Compression
/// </summary>
public static class ImageUtil
{
#region 圖片打包下載
/// <summary>
/// 下載圖片到本地,壓縮
/// </summary>
/// <param name="urlList">圖片列表</param>
/// <param name="curDirName">要壓縮文檔的路徑</param>
/// <param name="curFileName">壓縮后生成文檔保存路徑</param>
/// <returns></returns>
public static bool ImagePackZip(List<string> urlList, string curDirName, string curFileName)
{
return CommonException(() =>
{
//1.新建文件夾
if (!Directory.Exists(curDirName))
Directory.CreateDirectory(curDirName);
//2.下載文件到服務器臨時目錄
foreach (var url in urlList)
{
DownPicToLocal(url, curDirName + "\\");
Thread.Sleep(60);//加個延時,避免上一張圖還沒下載完就執(zhí)行下一張圖的下載操作
}
//3.壓縮文件夾
if (!File.Exists(curFileName))
ZipFile.CreateFromDirectory(curDirName, curFileName); //壓縮
//異步刪除壓縮前,下載的臨時文件
Task.Run(() =>
{
if (Directory.Exists(curDirName))
Directory.Delete(curDirName, true);
});
return true;
});
}
/// <summary>
/// 下載壓縮包
/// </summary>
/// <param name="targetfile">目標臨時文件地址</param>
/// <param name="filename">文件名</param>
public static bool DownePackZip(string targetfile, string filename)
{
return CommonException(() =>
{
FileInfo fileInfo = new FileInfo(targetfile);
HttpResponse rs = System.Web.HttpContext.Current.Response;
rs.Clear();
rs.ClearContent();
rs.ClearHeaders();
rs.AddHeader("Content-Disposition", "attachment;filename=" + $"{filename}");
rs.AddHeader("Content-Length", fileInfo.Length.ToString());
rs.AddHeader("Content-Transfer-Encoding", "binary");
rs.AddHeader("Pragma", "public");//這兩句解決https的cache緩存默認不給權(quán)限的問題
rs.AddHeader("Cache-Control", "max-age=0");
rs.ContentType = "application/octet-stream";
rs.ContentEncoding = System.Text.Encoding.GetEncoding("gb2312");
rs.WriteFile(fileInfo.FullName);
rs.Flush();
rs.End();
return true;
});
}
/// <summary>
/// 下載一張圖片到本地
/// </summary>
/// <param name="url"></param>
public static bool DownPicToLocal(string url, string localpath)
{
return CommonException(() =>
{
string fileprefix = DateTime.Now.ToString("yyyyMMddhhmmssfff");
var filename = $"{fileprefix}.jpg";
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.Timeout = 60000;
WebResponse response = request.GetResponse();
using (Stream reader = response.GetResponseStream())
{
FileStream writer = new FileStream(localpath + filename, FileMode.OpenOrCreate, FileAccess.Write);
byte[] buff = new byte[512];
int c = 0; //實際讀取的字節(jié)數(shù)
while ((c = reader.Read(buff, 0, buff.Length)) > 0)
{
writer.Write(buff, 0, c);
}
writer.Close();
writer.Dispose();
reader.Close();
reader.Dispose();
}
response.Close();
response.Dispose();
return true;
});
}
/// <summary>
/// 公用捕獲異常
/// </summary>
/// <param name="func"></param>
/// <returns></returns>
private static bool CommonException(Func<bool> func)
{
try
{
return func.Invoke();
}
catch (Exception ex)
{
return false;
}
}
#endregion
}
}
三,測試MVC代碼
using Common;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading;
using System.Web.Mvc;
namespace PackImageZip.Controllers
{
public class HomeController : Controller
{
private static object obj = new object();
public ActionResult Contact()
{
///鎖,多文件請求打包,存在并發(fā)情況
lock (obj)
{
var DownPicpath = System.Web.HttpContext.Current.Server.MapPath("/DownPicPackge");//服務器臨時文件目錄
string curFileName = DateTime.Now.ToString("yyyyMMddHHmmssfff") + ".zip";
///多次請求文件名一樣,睡眠一下
Thread.Sleep(2000);
////保存拉取服務器圖片文件夾
string curDirName = $"/{DateTime.Now.ToString("yyyyMMddHHmmssfff")}/";
List<string> urlList = new List<string>();
urlList.Add("https://cdn.duitang.com/uploads/item/201409/08/20140908155026_RdUwH.thumb.700_0.jpeg");
urlList.Add("https://cdn.duitang.com/uploads/item/201409/08/20140908155026_RdUwH.thumb.700_0.jpeg");
urlList.Add("https://cdn.duitang.com/uploads/item/201409/08/20140908155026_RdUwH.thumb.700_0.jpeg");
urlList.Add("https://cdn.duitang.com/uploads/item/201409/08/20140908155026_RdUwH.thumb.700_0.jpeg");
var isOk = ImageUtil.ImagePackZip(urlList, DownPicpath + curDirName, $"{DownPicpath}/{curFileName}");
var json = JsonConvert.SerializeObject(new { isok = isOk.ToString(), curFileName = curDirName });
return Content(json);
}
}
/// <summary>
/// 下載壓縮包
/// </summary>
/// <param name="curFileName">文件名</param>
/// <returns></returns>
public ActionResult DownePackZip(string curFileName)
{
try
{
curFileName = curFileName + ".zip";
var DownPicpath = System.Web.HttpContext.Current.Server.MapPath("/DownPicPackge");
var flag = ImageUtil.DownePackZip(DownPicpath + "/" + curFileName, curFileName);
////flag返回包之后就可以刪除包,因為包的已經(jīng)轉(zhuǎn)為流返回給客戶端,無需讀取源文件
if (flag && Directory.Exists(DownPicpath))
System.IO.File.Delete(DownPicpath + "/" + curFileName);
return Content(flag.ToString());
}
catch (Exception ex)
{
return Content(ex.Message);
}
}
}
}
以上就是本文的全部內(nèi)容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。
相關文章
C#如何將查詢到的數(shù)據(jù)庫里面的數(shù)據(jù)輸出到textbox控件
這篇文章主要介紹了C#如何將查詢到的數(shù)據(jù)庫里面的數(shù)據(jù)輸出到textbox控件問題,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2023-07-07
C#實現(xiàn)微信公眾號群發(fā)消息(解決一天只能發(fā)一次的限制)實例分享
經(jīng)過幾天研究網(wǎng)上的代碼和謝燦大神的幫忙,今天終于用C#實現(xiàn)了微信公眾號群發(fā)消息,現(xiàn)在分享一下2013-09-09

