C#服务端图片打包下载实现代码解析
一,设计多图片打包下载逻辑:
1,如果是要拉取腾讯云等资源服务器的图片,
2,我们先把远程图片拉取到本地的临时文件夹,
3,然后压缩临时文件夹,
4,压缩完删除临时文件夹,
5,返回压缩完给用户,
6,用户就去请求下载接口,当下载完后,删除压缩包
二,如下代码,ImageUtil
usingSystem;
usingSystem.Collections.Generic;
usingSystem.IO;
usingSystem.IO.Compression;
usingSystem.Linq;
usingSystem.Net;
usingSystem.Text;
usingSystem.Threading;
usingSystem.Threading.Tasks;
usingSystem.Web;
namespaceCommon
{
///
///要引用
///System.IO.Compression.FileSystem
///System.IO.Compression
///
publicstaticclassImageUtil
{
#region图片打包下载
///
///下载图片到本地,压缩
///
///图片列表
///要压缩文档的路径
///压缩后生成文档保存路径
///
publicstaticboolImagePackZip(ListurlList,stringcurDirName,stringcurFileName)
{
returnCommonException(()=>
{
//1.新建文件夹
if(!Directory.Exists(curDirName))
Directory.CreateDirectory(curDirName);
//2.下载文件到服务器临时目录
foreach(varurlinurlList)
{
DownPicToLocal(url,curDirName+"\\");
Thread.Sleep(60);//加个延时,避免上一张图还没下载完就执行下一张图的下载操作
}
//3.压缩文件夹
if(!File.Exists(curFileName))
ZipFile.CreateFromDirectory(curDirName,curFileName);//压缩
//异步删除压缩前,下载的临时文件
Task.Run(()=>
{
if(Directory.Exists(curDirName))
Directory.Delete(curDirName,true);
});
returntrue;
});
}
///
///下载压缩包
///
///目标临时文件地址
///文件名
publicstaticboolDownePackZip(stringtargetfile,stringfilename)
{
returnCommonException(()=>
{
FileInfofileInfo=newFileInfo(targetfile);
HttpResponsers=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缓存默认不给权限的问题
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();
returntrue;
});
}
///
///下载一张图片到本地
///
///
publicstaticboolDownPicToLocal(stringurl,stringlocalpath)
{
returnCommonException(()=>
{
stringfileprefix=DateTime.Now.ToString("yyyyMMddhhmmssfff");
varfilename=$"{fileprefix}.jpg";
HttpWebRequestrequest=(HttpWebRequest)WebRequest.Create(url);
request.Timeout=60000;
WebResponseresponse=request.GetResponse();
using(Streamreader=response.GetResponseStream())
{
FileStreamwriter=newFileStream(localpath+filename,FileMode.OpenOrCreate,FileAccess.Write);
byte[]buff=newbyte[512];
intc=0;//实际读取的字节数
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();
returntrue;
});
}
///
///公用捕获异常
///
///
///
privatestaticboolCommonException(Funcfunc)
{
try
{
returnfunc.Invoke();
}
catch(Exceptionex)
{
returnfalse;
}
}
#endregion
}
}
三,测试MVC代码
usingCommon;
usingNewtonsoft.Json;
usingSystem;
usingSystem.Collections.Generic;
usingSystem.IO;
usingSystem.Linq;
usingSystem.Threading;
usingSystem.Web.Mvc;
namespacePackImageZip.Controllers
{
publicclassHomeController:Controller
{
privatestaticobjectobj=newobject();
publicActionResultContact()
{
///锁,多文件请求打包,存在并发情况
lock(obj)
{
varDownPicpath=System.Web.HttpContext.Current.Server.MapPath("/DownPicPackge");//服务器临时文件目录
stringcurFileName=DateTime.Now.ToString("yyyyMMddHHmmssfff")+".zip";
///多次请求文件名一样,睡眠一下
Thread.Sleep(2000);
////保存拉取服务器图片文件夹
stringcurDirName=$"/{DateTime.Now.ToString("yyyyMMddHHmmssfff")}/";
ListurlList=newList();
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");
varisOk=ImageUtil.ImagePackZip(urlList,DownPicpath+curDirName,$"{DownPicpath}/{curFileName}");
varjson=JsonConvert.SerializeObject(new{isok=isOk.ToString(),curFileName=curDirName});
returnContent(json);
}
}
///
///下载压缩包
///
///文件名
///
publicActionResultDownePackZip(stringcurFileName)
{
try
{
curFileName=curFileName+".zip";
varDownPicpath=System.Web.HttpContext.Current.Server.MapPath("/DownPicPackge");
varflag=ImageUtil.DownePackZip(DownPicpath+"/"+curFileName,curFileName);
////flag返回包之后就可以删除包,因为包的已经转为流返回给客户端,无需读取源文件
if(flag&&Directory.Exists(DownPicpath))
System.IO.File.Delete(DownPicpath+"/"+curFileName);
returnContent(flag.ToString());
}
catch(Exceptionex)
{
returnContent(ex.Message);
}
}
}
}
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持毛票票。