C#|C# 批量打包下载图片(仅供参考,勿喷)

///
/// 定义一个图片的类
///
public class ATLRLAttachment
{
///
/// 字节流
///
public byte[] FileContent { get; set; }
///
/// 类型
///
public string FileExt { get; set; }
///
/// 名称
///
public string FileName { get; set; }
}
///
/// 通过图片地址将图片转换成字节流
///
/// 图片地址
/// 字节流
public byte[] GetImageByte(string url)
{
FileStream fs = new FileStream(url, FileMode.Open);
byte[] byData = https://www.it610.com/article/new byte[fs.Length];
fs.Read(byData, 0, byData.Length);
fs.Close();
return byData;
}
///
/// 批量下载
///
/// 下载集合
public void ImageDown(IEnumerable models)
{
string FileToZip = DateTime.Now.ToString("yyyyMMdd") + ".zip";
string path = AppDomain.CurrentDomain.BaseDirectory;
string url = string.Format(@"{0}Content\TemporaryImage", path);
#region 删除压缩包节约空间(每次打包下载都会在上面的"url"中创建一个.zip的压缩包)
DirectoryInfo dir = new DirectoryInfo(url);
FileSystemInfo[] fileinfo = dir.GetFileSystemInfos(); //返回目录中所有文件和子目录
foreach (FileSystemInfo i in fileinfo)
{
System.IO.File.Delete(i.FullName); //删除文件夹下的文件
}
#endregion
path = string.Format(@"{0}\\{1}", url, FileToZip);
using (FileStream ms = new FileStream(path, FileMode.Create))
{
using (ZipOutputStream zip = new ZipOutputStream(ms))
{
zip.SetLevel(9);
foreach (ATLRLAttachment m in models)
{
ZipEntry entry = new ZipEntry(m.FileName);
zip.PutNextEntry(entry);
zip.Write(m.FileContent, 0, m.FileContent.Length);
}
zip.Finish();
zip.Close();
}
}
FileInfo fileInfo = new FileInfo(path);
Response.Clear();
Response.ClearContent();
Response.ClearHeaders();
Response.AddHeader("Content-Disposition", string.Format("attachment; filename={0}.zip", DateTime.Now.ToString("yyyyMMdd")));
Response.AddHeader("Content-Length", fileInfo.Length.ToString());
Response.AddHeader("Content-Transfer-Encoding", "binary");
Response.ContentType = "application/octet-stream";
Response.ContentEncoding = System.Text.Encoding.GetEncoding("utf-8");
Response.WriteFile(fileInfo.FullName);
Response.Flush();
Response.End();
}
#endregion
测试:
public void DownFun1()//测试例子
{
byte[] result = GetImageByte(@"D://111.jpg");
var list = new[] { new ATLRLAttachment { FileContent = result, FileExt = ".jpg", FileName = "Name.jpg" }, new ATLRLAttachment { FileContent = result, FileExt = ".jpg", FileName = "Name.jpg" } };
ImageDown(list);
}

【C#|C# 批量打包下载图片(仅供参考,勿喷)】 public void DownFun(string ids)//我的图片路径保存在数据库中根据前台传过来的"id"调取数据(仅供参考,我程序的方法)
{
//Ssc_BidFor_Order(); 我数据表
var Bll = new CityCard.Web.Admin.BLL.Ssc_BidFor_Order();
IList mList = new List();
foreach (var id in ids.Split(',').Select(a => int.Parse(a)).ToList())
{
var item = new ATLRLAttachment();
var model = Bll.Get(id);
item.FileContent = GetImageByte(model.Ipath); //文中ipath是物理路径
item.FileExt = model.Ipath.Substring(model.Ipath.LastIndexOf(".")); //图片的后缀
item.FileName =model.IdCard+item.FileExt; //对名称可自定义(比如命名为1.jpg);
mList.Add(item);
}
ImageDown(mList);
}
参考文献:https://www.cnblogs.com/chenxygx/p/5265338.html 这位老哥写的很好我是摘除了部分。

    推荐阅读