.netcore+vue 实现压缩文件下载
思路是在后台将文件夹整体压缩为zip格式的压缩包,并返回文件流到前端,然后前端接收文件流实现浏览器下载的功能。后端代码,将Copypublic async Task DownloadFiles(DownLoadModel input){if (!Directory.Exists(input.pathUrl)){throw new UserFriendlyException(“当前要下载的文件夹不存
思路是在后台将文件夹整体压缩为zip格式的压缩包,并返回文件流到前端,然后前端接收文件流实现浏览器下载的功能。
后端代码,将
Copy
public async Task DownloadFiles(DownLoadModel input)
{
if (!Directory.Exists(input.pathUrl))
{
throw new UserFriendlyException(“当前要下载的文件夹不存在或已删除”);
}
var zipFileUrl = _configurationRoot[“downLoadUrlConf:downloadZipFileUrl”];
if (File.Exists(zipFileUrl))
{
File.Delete(zipFileUrl);
}
ZipHelper.CreateZip(input.pathUrl, zipFileUrl);
var memoryStream = new MemoryStream();
using (var stream = new FileStream(zipFileUrl, FileMode.Open))
{
await stream.CopyToAsync(memoryStream);
}
memoryStream.Seek(0, SeekOrigin.Begin);
return new FileStreamResult(memoryStream, “application/octet-stream”);//文件流方式,指定文件流对应的ContenType。
}
Copy
public static class ZipHelper
{
///
/// 压缩文件
///
///
///
public static void CreateZip(string sourceFilePath, string destinationZipFilePath)
{
if (sourceFilePath[sourceFilePath.Length - 1] != System.IO.Path.DirectorySeparatorChar)
sourceFilePath += System.IO.Path.DirectorySeparatorChar;
ZipOutputStream zipStream = new ZipOutputStream(File.Create(destinationZipFilePath));
zipStream.SetLevel(6); // 压缩级别 0-9
CreateZipFiles(sourceFilePath, zipStream, sourceFilePath);
zipStream.Finish();
zipStream.Close();
}
/// <summary>
/// 递归压缩文件
/// </summary>
/// <param name="sourceFilePath">待压缩的文件或文件夹路径</param>
/// <param name="zipStream">
/// <param name="staticFile"></param>
private static void CreateZipFiles(string sourceFilePath, ZipOutputStream zipStream, string staticFile)
{
Crc32 crc = new Crc32();
string[] filesArray = Directory.GetFileSystemEntries(sourceFilePath);
foreach (string file in filesArray)
{
if (Directory.Exists(file)) //如果当前是文件夹,递归
{
CreateZipFiles(file, zipStream, staticFile);
}
else //如果是文件,开始压缩
{
FileStream fileStream = File.OpenRead(file);
byte[] buffer = new byte[fileStream.Length];
fileStream.Read(buffer, 0, buffer.Length);
string tempFile = file.Substring(staticFile.LastIndexOf("\\") + 1);
ZipEntry entry = new ZipEntry(tempFile);
entry.DateTime = DateTime.Now;
entry.Size = fileStream.Length;
fileStream.Close();
crc.Reset();
crc.Update(buffer);
entry.Crc = crc.Value;
zipStream.PutNextEntry(entry);
zipStream.Write(buffer, 0, buffer.Length);
}
}
}
}
其中CreateZip方法传入一个源文件的路径,一个目标文件的路径,这里我的目标文件设置在appsetting.json里是个临时路径,只为前端当次下载使用。这样我们就在后台将数据以压缩包的形式压缩好,并返回数据流给前端了。
1.2 vue 下载压缩文件#
Copy
<el-button
icon=“el-icon-download”
size=“mini”
type=“primary”
class=“pull-right”
@click=“downloadFile”
>下载文件到本地
Copy
downloadFile() {
this.loading = true;
let postData = { pathUrl: this.filePathMag };
AjaxHelper.post(this.downLoadUrl, postData, {
responseType: “blob”,
}).then((res) => {
// 处理返回的文件流
const content = res.data;
const blob = new Blob([content], { type: “application/zip” });
const fileName = this.tenant.name + “配置信息.zip”;
if (“download” in document.createElement(“a”)) {
// 非IE下载
const elink = document.createElement(“a”);
elink.download = fileName;
elink.style.display = “none”;
elink.href = URL.createObjectURL(blob);
document.body.appendChild(elink);
elink.click();
URL.revokeObjectURL(elink.href); // 释放URL 对象
document.body.removeChild(elink);
} else {
// IE10+下载
navigator.msSaveBlob(blob, fileName);
}
this.loading = false;
});
},
龙华大道1号http://www.kinghill.cn/LongHuaDaDao1Hao/index.html
更多推荐
所有评论(0)