思路:

1、把网络图片下载到服务器本地。

2、读取服务器图片的文件流

3、使用zip帮助类,把图片文件流写进zip文件流。

4、如果是文件服务器,把zip文件流 推送文件服务器,生成zip的下载url

5、如果我mvc 可以把zip的文件流返回到前端,进行格式的转换。

业务代码:

public async Task<FileStreamResult> DownloadScreenshotsZipStream()
{
List<ScreenshotsModel> models = new List<ScreenshotsModel>()
{
new ScreenshotsModel(){ ScreenshotsUrl="https://...jpg",Lablel="1号"},
new ScreenshotsModel(){ ScreenshotsUrl="https://...jpg",Lablel="2号"},
new ScreenshotsModel(){ ScreenshotsUrl="https://....jpg",Lablel="3号"},
new ScreenshotsModel(){ ScreenshotsUrl="https://....jpg",Lablel="4号"}
};
var randomParh = Guid.NewGuid().ToString();
var randomParhZipFileUrl = Guid.NewGuid().ToString();
string savePath = $@"D:\ScreenshotsUrl\{randomParh}\";
//文件创建
if (!Directory.Exists(savePath))
{
Directory.CreateDirectory(savePath);
}
WebClient mywebclient = new WebClient();
foreach (var item in models)
{
//下载文件
mywebclient.DownloadFile(item.ScreenshotsUrl, savePath + models.IndexOf(item).ToString() + @".png");
}
//指定打包的文件夹路径
string src = $@"D:\ScreenshotsUrl\{randomParh}";
//打包之后,zip存到哪个路径
string zipFileUrl = $@"D:\ScreenshotsUrl\{randomParhZipFileUrl}\NormalScreenshot.zip";
if (!Directory.Exists(Path.GetDirectoryName(zipFileUrl)))
{
Directory.CreateDirectory(Path.GetDirectoryName(zipFileUrl));
}
ZipHelper zipHelper = new ZipHelper();
bool flag = zipHelper.Zip(src, zipFileUrl); var memoryStream = new MemoryStream();
using (var stream = new FileStream(zipFileUrl, FileMode.Open))
{
stream.CopyToAsync(memoryStream);
}
memoryStream.Seek(0, SeekOrigin.Begin);
if (Directory.Exists(savePath))
{
//删除下载的截图和zip文件
Directory.Delete(savePath, true);
}
if (Directory.Exists(Path.GetDirectoryName(zipFileUrl)))
{
//删除下载的截图和zip文件
Directory.Delete(Path.GetDirectoryName(zipFileUrl), true);
}
return new FileStreamResult(memoryStream, "application/octet-stream");//文件流方式,指定文件流对应的ContenType。
//return new FileStreamResult(memoryStream, "application/zip");//文件流方式,指定文件流对应的ContenType。
}
public async Task<MessageModel<string>> DownloadScreenshotsZipOSS()
{
List<ScreenshotsModel> models = new List<ScreenshotsModel>()
{
new ScreenshotsModel(){ ScreenshotsUrl="https://..jpg",Lablel="1号"},
new ScreenshotsModel(){ ScreenshotsUrl="https://..jpg",Lablel="2号"},
new ScreenshotsModel(){ ScreenshotsUrl="https://..jpg",Lablel="3号"},
new ScreenshotsModel(){ ScreenshotsUrl="https://..jpg",Lablel="4号"}
};
var randomParh = Guid.NewGuid().ToString();
var randomParhZipFileUrl = Guid.NewGuid().ToString();
string savePath = $@"D:\ScreenshotsUrl\{randomParh}\";
//文件创建
if (!Directory.Exists(savePath))
{
Directory.CreateDirectory(savePath);
}
WebClient mywebclient = new WebClient();
foreach (var item in models)
{
//下载文件
mywebclient.DownloadFile(item.ScreenshotsUrl, savePath + models.IndexOf(item).ToString() + @".png");
}
//指定打包的文件夹路径
string src = $@"D:\ScreenshotsUrl\{randomParh}";
//打包之后,zip存到哪个路径
string zipFileUrl = $@"D:\ScreenshotsUrl\{randomParhZipFileUrl}\NormalScreenshot.zip";
if (!Directory.Exists(Path.GetDirectoryName(zipFileUrl)))
{
Directory.CreateDirectory(Path.GetDirectoryName(zipFileUrl));
}
ZipHelper zipHelper = new ZipHelper();
bool flag = zipHelper.Zip(src, zipFileUrl); Stream stream = GetStream.FromFilePath(zipFileUrl);
var ossurl = OssUploadHelper.SaveContent(stream, "zip");
stream.Dispose();
stream.Close();
if (Directory.Exists(savePath))
{
//删除下载的截图和zip文件
Directory.Delete(savePath, true);
}
if (Directory.Exists(Path.GetDirectoryName(zipFileUrl)))
{
//删除下载的截图和zip文件
Directory.Delete(Path.GetDirectoryName(zipFileUrl), true);
}
return MessageModel<string>.Success(ossurl);
}
public class ScreenshotsModel
{
public string ScreenshotsUrl { get; set; }
public string Lablel { get; set; }
}

zip帮助类:

/// <summary>
/// 压缩解压Zip的工具类
/// </summary>
public class ZipHelper
{ #region 扩展类 private string rootPath = string.Empty; #region 压缩 /// <summary>
/// 递归压缩文件夹的内部方法
/// </summary>
/// <param name="folderToZip">要压缩的文件夹路径</param>
/// <param name="zipStream">压缩输出流</param>
/// <param name="parentFolderName">此文件夹的上级文件夹</param>
/// <returns></returns>
private bool ZipDirectory(string folderToZip, ZipOutputStream zipStream, string parentFolderName)
{
bool result = true;
string[] folders, files;
ZipEntry ent = null;
FileStream fs = null;
Crc32 crc = new Crc32(); try
{
string entName = folderToZip.Replace(this.rootPath, string.Empty) + "/";
//Path.Combine(parentFolderName, Path.GetFileName(folderToZip) + "/")
ent = new ZipEntry(entName);
zipStream.PutNextEntry(ent);
zipStream.Flush(); files = Directory.GetFiles(folderToZip);
foreach (string file in files)
{
fs = File.OpenRead(file);
byte[] buffer = new byte[fs.Length];
fs.Read(buffer, 0, buffer.Length);
ent = new ZipEntry(entName + Path.GetFileName(file));
ent.DateTime = DateTime.Now;
ent.Size = fs.Length; fs.Close(); crc.Reset();
crc.Update(buffer); ent.Crc = crc.Value;
zipStream.PutNextEntry(ent);
zipStream.Write(buffer, 0, buffer.Length);
} }
catch
{
result = false;
}
finally
{
if (fs != null)
{
fs.Close();
fs.Dispose();
}
if (ent != null)
{
ent = null;
}
GC.Collect();
GC.Collect(1);
} folders = Directory.GetDirectories(folderToZip);
foreach (string folder in folders)
if (!ZipDirectory(folder, zipStream, folderToZip))
return false; return result;
} /// <summary>
/// 压缩文件夹
/// </summary>
/// <param name="folderToZip">要压缩的文件夹路径</param>
/// <param name="zipedFile">压缩文件完整路径</param>
/// <param name="password">密码</param>
/// <returns>是否压缩成功</returns>
public bool ZipDirectory(string folderToZip, string zipedFile, string password)
{
bool result = false;
if (!Directory.Exists(folderToZip))
return result; ZipOutputStream zipStream = new ZipOutputStream(File.Create(zipedFile));
zipStream.SetLevel(6);
if (!string.IsNullOrEmpty(password)) zipStream.Password = password; result = ZipDirectory(folderToZip, zipStream, ""); zipStream.Finish();
zipStream.Close(); return result;
} /// <summary>
/// 压缩文件夹
/// </summary>
/// <param name="folderToZip">要压缩的文件夹路径</param>
/// <param name="zipedFile">压缩文件完整路径</param>
/// <returns>是否压缩成功</returns>
public bool ZipDirectory(string folderToZip, string zipedFile)
{
bool result = ZipDirectory(folderToZip, zipedFile, null);
return result;
} /// <summary>
/// 压缩文件
/// </summary>
/// <param name="fileToZip">要压缩的文件全名</param>
/// <param name="zipedFile">压缩后的文件名</param>
/// <param name="password">密码</param>
/// <returns>压缩结果</returns>
public bool ZipFile(string fileToZip, string zipedFile, string password)
{
bool result = true;
ZipOutputStream zipStream = null;
FileStream fs = null;
ZipEntry ent = null; if (!File.Exists(fileToZip))
return false; try
{
fs = File.OpenRead(fileToZip);
byte[] buffer = new byte[fs.Length];
fs.Read(buffer, 0, buffer.Length);
fs.Close(); fs = File.Create(zipedFile);
zipStream = new ZipOutputStream(fs);
if (!string.IsNullOrEmpty(password)) zipStream.Password = password;
ent = new ZipEntry(Path.GetFileName(fileToZip));
zipStream.PutNextEntry(ent);
zipStream.SetLevel(6); zipStream.Write(buffer, 0, buffer.Length); }
catch
{
result = false;
}
finally
{
if (zipStream != null)
{
zipStream.Finish();
zipStream.Close();
}
if (ent != null)
{
ent = null;
}
if (fs != null)
{
fs.Close();
fs.Dispose();
}
}
GC.Collect();
GC.Collect(1); return result;
} /// <summary>
/// 压缩文件
/// </summary>
/// <param name="fileToZip">要压缩的文件全名</param>
/// <param name="zipedFile">压缩后的文件名</param>
/// <returns>压缩结果</returns>
public bool ZipFile(string fileToZip, string zipedFile)
{
bool result = ZipFile(fileToZip, zipedFile, null);
return result;
} /// <summary>
/// 压缩文件或文件夹
/// </summary>
/// <param name="fileToZip">要压缩的路径</param>
/// <param name="zipedFile">压缩后的文件名</param>
/// <param name="password">密码</param>
/// <returns>压缩结果</returns>
public bool Zip(string fileToZip, string zipedFile, string password)
{
bool result = false;
if (Directory.Exists(fileToZip))
{
this.rootPath = Path.GetDirectoryName(fileToZip);
result = ZipDirectory(fileToZip, zipedFile, password);
}
else if (File.Exists(fileToZip))
{
this.rootPath = Path.GetDirectoryName(fileToZip);
result = ZipFile(fileToZip, zipedFile, password);
}
return result;
} /// <summary>
/// 压缩文件或文件夹
/// </summary>
/// <param name="fileToZip">要压缩的路径</param>
/// <param name="zipedFile">压缩后的文件名</param>
/// <returns>压缩结果</returns>
public bool Zip(string fileToZip, string zipedFile)
{
bool result = Zip(fileToZip, zipedFile, null);
return result; } #endregion #region 解压 /// <summary>
/// 解压功能(解压压缩文件到指定目录)
/// </summary>
/// <param name="fileToUnZip">待解压的文件</param>
/// <param name="zipedFolder">指定解压目标目录</param>
/// <param name="password">密码</param>
/// <returns>解压结果</returns>
public bool UnZip(string fileToUnZip, string zipedFolder, string password)
{
bool result = true;
FileStream fs = null;
ZipInputStream zipStream = null;
ZipEntry ent = null;
string fileName; if (!File.Exists(fileToUnZip))
return false; if (!Directory.Exists(zipedFolder))
Directory.CreateDirectory(zipedFolder); try
{
zipStream = new ZipInputStream(File.OpenRead(fileToUnZip));
if (!string.IsNullOrEmpty(password)) zipStream.Password = password;
while ((ent = zipStream.GetNextEntry()) != null)
{
if (!string.IsNullOrEmpty(ent.Name))
{
fileName = Path.Combine(zipedFolder, ent.Name);
fileName = fileName.Replace('/', '\\');//change by Mr.HopeGi if (fileName.EndsWith("\\"))
{
Directory.CreateDirectory(fileName);
continue;
} fs = File.Create(fileName);
int size = 2048;
byte[] data = new byte[size];
while (true)
{
size = zipStream.Read(data, 0, data.Length);
if (size > 0)
fs.Write(data, 0, data.Length);
else
break;
}
}
}
}
catch
{
result = false;
}
finally
{
if (fs != null)
{
fs.Close();
fs.Dispose();
}
if (zipStream != null)
{
zipStream.Close();
zipStream.Dispose();
}
if (ent != null)
{
ent = null;
}
GC.Collect();
GC.Collect(1);
}
return result;
} /// <summary>
/// 解压功能(解压压缩文件到指定目录)
/// </summary>
/// <param name="fileToUnZip">待解压的文件</param>
/// <param name="zipedFolder">指定解压目标目录</param>
/// <returns>解压结果</returns>
public bool UnZip(string fileToUnZip, string zipedFolder)
{
bool result = UnZip(fileToUnZip, zipedFolder, null);
return result;
} #endregion #endregion /// <summary>
/// 解压缩一个zip文件
/// </summary>
/// <param name="inputStream">要解压的zip文件</param>
/// <param name="password">zip文件的密码</param>
public static IList<KeyValue<Stream>> UnZipStream(Stream inputStream, string password = "")
{
inputStream.Position = 0; IList<KeyValue<Stream>> result = new List<KeyValue<Stream>>(); ZipInputStream zipStream = new ZipInputStream(inputStream);
if (password != "")
{
zipStream.Password = password;
} try
{
ZipEntry theEntry;
while ((theEntry = zipStream.GetNextEntry()) != null)
{
MemoryStream memoryStream = new MemoryStream();
int size = 2048;
byte[] data = new byte[2048];
while (true)
{
size = zipStream.Read(data, 0, data.Length);
if (size > 0)
memoryStream.Write(data, 0, size);
else
break;
}
memoryStream.Position = 0;
result.Add(new KeyValue<Stream>
{
Key = theEntry.Name,
Value = memoryStream
});
}
}
catch (Exception ex)
{
throw ex;
}
finally
{
zipStream.Close();
} //返回自然排序的文件列表
return result.OrderBy(a => a.Key.Split('.')[0], new StringCompare()).ToList();
} /// <summary>
/// 解压缩文件到指定目录
/// </summary>
/// <param name="zipPath"></param>
/// <param name="unZipFolder"></param>
/// <returns></returns>
public static void UnZipFromPathToFolder(string zipPath, string unZipFolder)
{
//解压缩文件到指定目录
new UnZipDir(zipPath, unZipFolder);
} /// <summary>
/// 解压二进制ZIP文件到二进制文件数组
/// </summary>
/// <param name="buffer"></param>
/// <returns></returns>
public static IList<ZipFileBuffer> UnZipFromBytesToBytes(byte[] buffer)
{
//创建工作目录
string workFolder = Path.GetTempPath() + Guid.NewGuid().ToString().Replace("-", "").ToUpper() + "\\";
DirectoryInfo workDirectory = Directory.CreateDirectory(workFolder);
string zipPath = workFolder + "data.zip";
string unZipFolder = workFolder + "data"; //保存zip临时文件
FileStream fileStream = new FileStream(zipPath, FileMode.Create);
BinaryWriter binaryWriter = new BinaryWriter(fileStream);
binaryWriter.Write(buffer);
binaryWriter.Close(); //解压缩zip文件到临时目录
UnZipFromPathToFolder(zipPath, unZipFolder); //读取全部文件到数组
IList<FileInfo> fileList = new List<FileInfo>();
GetDirectoryFiles(fileList, new DirectoryInfo(unZipFolder)); //读取全部文件到输出返回
IList<ZipFileBuffer> result = new List<ZipFileBuffer>(); foreach (FileInfo file in fileList)
{
result.Add(new ZipFileBuffer
{
RelativePath = file.FullName.Replace(unZipFolder + "\\", "").Replace("\\", "/"),
FileBuffer = File.ReadAllBytes(file.FullName)
});
} //删除工作目录
workDirectory.Delete(true); return result;
} /// <summary>
/// 解压二进制ZIP文件到指定目录
/// </summary>
/// <param name="buffer"></param>
/// <param name="unZipFolder"></param>
public static void UnZipFromBytesToFolder(byte[] buffer, string unZipFolder)
{
//创建工作目录
string workFolder = Path.GetTempPath() + Guid.NewGuid().ToString().Replace("-", "").ToUpper() + "\\";
DirectoryInfo workDirectory = Directory.CreateDirectory(workFolder);
string zipPath = workFolder + "data.zip"; //保存zip临时文件
FileStream fileStream = new FileStream(zipPath, FileMode.Create);
BinaryWriter binaryWriter = new BinaryWriter(fileStream);
binaryWriter.Write(buffer);
binaryWriter.Close(); //解压缩zip文件到指定目录
UnZipFromPathToFolder(zipPath, unZipFolder); //删除工作目录
workDirectory.Delete(true);
} #region 私有方法 /// <summary>
/// 遍历文件夹中的所有文件
/// </summary>
/// <param name="fileList"></param>
/// <param name="dic"></param>
private static void GetDirectoryFiles(IList<FileInfo> fileList, DirectoryInfo dic)
{
foreach (FileInfo file in dic.GetFiles())
{
fileList.Add(file);
}
foreach (DirectoryInfo subdic in dic.GetDirectories())
{
GetDirectoryFiles(fileList, subdic);
}
} #endregion }

c# 把网络图片http://....png 打包成zip文件的更多相关文章

  1. 十一、springboot 配置log4j2以及打包成zip文件

    前言 其实我们前面已经配置了日志,但是最近总感觉日志日志格式看的不舒服,并且每次打包都是一个jar 文件,lib都包含在jar 中,每次做很小的修改都需要重新替换jar文件,jar文件会比较大,传输起 ...

  2. php将文件夹打包成zip文件

    function addFileToZip($path,$zip){    $handler=opendir($path); //打开当前文件夹由$path指定.    while(($filenam ...

  3. 【原】Python用例:将指定文件或目录打包成zip文件

    #This Demo is used to compress files to .zip file #Base on Windows import os import time #The files ...

  4. PHP将多级目录打包成zip文件

    最近接触PHP,需要用到zip压缩,在网上搜索的一大堆,发现代码都不低于50行.  而且调用还很费事(基础太少看不懂).让我收获的是Php提供有一个ZipArchive类,并有如下方法. bool a ...

  5. Vue -- webpack 项目自动打包压缩成zip文件

    这段时间用 Vue2.0 开发项目,每次打包都会用到 npm run build 命令,但是每次部署时给后端发包都要手动zip压缩,这样一两次还行,但遇到项目板块测试和临时加急功能测试的时候,一天可能 ...

  6. 将多张图片打包成zip包,一起上传

    1.前端页面 <div class="mod-body" id="showRW" style="text-align: center;font- ...

  7. springboot中使用freemarker生成word文档并打包成zip下载(简历)

    一.设计出的简历模板图以及给的简历小图标切图         二.按照简历模板图新建简历word文件 :${字段名},同时将图片插入到word中,并将建好的word文件另存为xml文件:    三.直 ...

  8. vue-webpack项目自动打包压缩成zip文件批处理

    为什么需要这个? 使用vue框架开发项目,npm run build这个命令会一直用到,如果需要给后端发包,那你还要打包成zip格式的压缩包,特别是项目提测的时候,一天可能要执行重复好几次,所以才有了 ...

  9. java将文件打包成ZIP压缩文件的工具类实例

    package com.lanp; import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import ja ...

随机推荐

  1. 2021.11.05 eleveni的水省选题的记录

    2021.11.05 eleveni的水省选题的记录 因为eleveni比较菜,但是eleveni不想写绿题(总不能说是被绿题虐得不想写),eleveni决定继续水noip原题. --实际上菜菜的el ...

  2. 【Java分享客栈】从线上环境摘取了四个代码优化记录分享给大家

    前言 因为前段时间新项目已经完成目前趋于稳定,所以最近我被分配到了公司的运维组,负责维护另外一个项目,包含处理客户反馈的日常问题,以及对系统缺陷进行优化. 经过了接近两周的维护,除了日常问题以外,代码 ...

  3. 记一次jenkins发送邮件报错 一直报错 Could not send email as a part of the post-build publishers问题

    写在前面 虽然Jenkins是开源.免费的,好处很多,但有些功能上的使用,我个人还是很不喜欢,感觉用起来特别麻烦.繁琐. 为什么? 就拿这个邮件配置来说吧,因重装系统,电脑需要配置很多东西,结果今天就 ...

  4. 9.1 Linux存储结构和文件系统

    1. 存储结构 Linux系统中的一切文件都是从"根"目录(/)开始的,并按照文件系统层次标准(FHS)采用倒树状结构来存放文件,以及定义了常见目录的用途. 目录名称 应放置文件的 ...

  5. XCTF练习题---MISC---2017_Dating_in_Singapore

    XCTF练习题---MISC---2017_Dating_in_Singapore flag:HITB{CTFFUN} 解题步骤: 1.观察题目,下载附件 2.打开附件后发现是一张日历,还是新加坡的, ...

  6. 使用 Python 来自动回微信

    准备 Python3 Python Itchat库(可以通过pip install itchat来安装) (可选)Python Pymongo库(可以通过pip install pymongo来安装) ...

  7. Java学习笔记-基础语法Ⅵ-异常

    异常 对于异常,JVM默认处理方案为:把异常名称.异常原因以及异常出现的位置等信息输出在控制台,并且程序停止执行 异常处理方式一:try ... catch public class Demo { p ...

  8. HttpResponse,render,redirect,静态文件配置,request对象方法,pycharm连接MySQL,django连接MySQL,django ORM

    HttpResponse 主要用于返回字符串类型的数据 def index(request): return HttpResponse('index页面') 在页面中就会显示 index页面 rend ...

  9. PHP_SESSION学习小结

    PHP Session PHP session 变量用于存储关于用户会话(session)的信息,或者更改用户会话(session)的设置.Session 变量存储单一用户的信息,并且对于应用程序中的 ...

  10. SQL查询与SQL优化[姊妹篇.第四弹]

    在上一篇文章中,我们一起了解了关系模型与关系运算相关的知识,接下来我们一起谈谈,面对复杂的关系数据,我们如何来优化,SQL如何玩转更优呢? 在上一篇中抛出了4个关于优化方面的问题: 1.返回表中0.0 ...