C#服務(wù)端圖片打包下載實(shí)現(xiàn)代碼解析
一,設(shè)計(jì)多圖片打包下載邏輯:
1,如果是要拉取騰訊云等資源服務(wù)器的圖片,
2,我們先把遠(yuǎn)程圖片拉取到本地的臨時(shí)文件夾,
3,然后壓縮臨時(shí)文件夾,
4,壓縮完刪除臨時(shí)文件夾,
5,返回壓縮完給用戶,
6,用戶就去請(qǐng)求下載接口,當(dāng)下載完后,刪除壓縮包
二,如下代碼,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.下載文件到服務(wù)器臨時(shí)目錄
foreach (var url in urlList)
{
DownPicToLocal(url, curDirName + "\\");
Thread.Sleep(60);//加個(gè)延時(shí),避免上一張圖還沒(méi)下載完就執(zhí)行下一張圖的下載操作
}
//3.壓縮文件夾
if (!File.Exists(curFileName))
ZipFile.CreateFromDirectory(curDirName, curFileName); //壓縮
//異步刪除壓縮前,下載的臨時(shí)文件
Task.Run(() =>
{
if (Directory.Exists(curDirName))
Directory.Delete(curDirName, true);
});
return true;
});
}
/// <summary>
/// 下載壓縮包
/// </summary>
/// <param name="targetfile">目標(biāo)臨時(shí)文件地址</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緩存默認(rèn)不給權(quán)限的問(wè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; //實(shí)際讀取的字節(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
}
}
三,測(cè)試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()
{
///鎖,多文件請(qǐng)求打包,存在并發(fā)情況
lock (obj)
{
var DownPicpath = System.Web.HttpContext.Current.Server.MapPath("/DownPicPackge");//服務(wù)器臨時(shí)文件目錄
string curFileName = DateTime.Now.ToString("yyyyMMddHHmmssfff") + ".zip";
///多次請(qǐng)求文件名一樣,睡眠一下
Thread.Sleep(2000);
////保存拉取服務(wù)器圖片文件夾
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返回包之后就可以刪除包,因?yàn)榘囊呀?jīng)轉(zhuǎn)為流返回給客戶端,無(wú)需讀取源文件
if (flag && Directory.Exists(DownPicpath))
System.IO.File.Delete(DownPicpath + "/" + curFileName);
return Content(flag.ToString());
}
catch (Exception ex)
{
return Content(ex.Message);
}
}
}
}
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
- c# 斷點(diǎn)續(xù)傳的實(shí)現(xiàn)
- C# FileStream實(shí)現(xiàn)多線程斷點(diǎn)續(xù)傳
- C# 文件下載之?dāng)帱c(diǎn)續(xù)傳實(shí)現(xiàn)代碼
- C#文件斷點(diǎn)續(xù)傳實(shí)現(xiàn)方法
- C#實(shí)現(xiàn)文件斷點(diǎn)續(xù)傳下載的方法
- c#實(shí)現(xiàn)斷點(diǎn)續(xù)傳功能示例分享
- C#實(shí)現(xiàn)支持?jǐn)帱c(diǎn)續(xù)傳多線程下載客戶端工具類
- c# 實(shí)現(xiàn)文件上傳下載功能的實(shí)例代碼
- C#怎樣實(shí)現(xiàn)文件下載斷點(diǎn)續(xù)傳
相關(guān)文章
基于C#實(shí)現(xiàn)文字轉(zhuǎn)語(yǔ)音功能
這篇文章將在C#中集成一個(gè)語(yǔ)音對(duì)象SpeechSynthesizer,可以根據(jù)填入的文字內(nèi)容自動(dòng)解析成語(yǔ)音并使用系統(tǒng)揚(yáng)聲器進(jìn)行語(yǔ)音播報(bào),感興趣的小伙伴可以了解下2025-02-02
C#如何將查詢到的數(shù)據(jù)庫(kù)里面的數(shù)據(jù)輸出到textbox控件
這篇文章主要介紹了C#如何將查詢到的數(shù)據(jù)庫(kù)里面的數(shù)據(jù)輸出到textbox控件問(wèn)題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2023-07-07
C#實(shí)現(xiàn)微信公眾號(hào)群發(fā)消息(解決一天只能發(fā)一次的限制)實(shí)例分享
經(jīng)過(guò)幾天研究網(wǎng)上的代碼和謝燦大神的幫忙,今天終于用C#實(shí)現(xiàn)了微信公眾號(hào)群發(fā)消息,現(xiàn)在分享一下2013-09-09
C#下載網(wǎng)頁(yè)并在控制臺(tái)輸出的方法
這篇文章主要介紹了C#下載網(wǎng)頁(yè)并在控制臺(tái)輸出的方法,涉及C#基于http協(xié)議進(jìn)行網(wǎng)頁(yè)抓取及控制臺(tái)輸出顯示的相關(guān)技巧,需要的朋友可以參考下2015-07-07
C# log4net 日志輸出的實(shí)現(xiàn)示例
本文主要介紹了C# log4net 日志輸出的實(shí)現(xiàn)示例,文中通過(guò)示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2021-10-10

