.netcore+vue 實(shí)現(xiàn)壓縮文件下載功能
一.前言
目前接觸的項(xiàng)目中,給定的需求是將系統(tǒng)內(nèi)所有用戶的數(shù)據(jù)整理好,并保存到文件夾內(nèi),目的主要是防止用戶在實(shí)施人員已配置好的基礎(chǔ)上由于不熟悉系統(tǒng),導(dǎo)致的誤刪或者誤操作。減少實(shí)施人員的配置工作。我首先想到的就是將數(shù)據(jù)導(dǎo)入到Excel中,并以各個(gè)用戶的名稱命名文件夾做好分類。
vue下實(shí)現(xiàn)Excel導(dǎo)入這個(gè)我們見(jiàn)的比較多了,當(dāng)時(shí)我也確實(shí)實(shí)現(xiàn)了下載Excel的功能,但是后續(xù)發(fā)現(xiàn)保存的文件都在服務(wù)器上,那就有一個(gè)問(wèn)題了,實(shí)施人員是通過(guò)頁(yè)面點(diǎn)擊的一鍵保存按鈕,數(shù)據(jù)也確實(shí)保存了,但是卻是在服務(wù)器上,如果想實(shí)時(shí)看到數(shù)據(jù)呢,是不是還要去服務(wù)器上拷貝一份下來(lái)。相對(duì)來(lái)講確實(shí)比較繁瑣,所以整理了下載壓縮文件到本地的功能,一起看一下怎么實(shí)現(xiàn)的吧。
1.1.net core 壓縮文件
思路是在后臺(tái)將文件夾整體壓縮為zip格式的壓縮包,并返回文件流到前端,然后前端接收文件流實(shí)現(xiàn)瀏覽器下載的功能。
后端代碼,將
public async Task<FileStreamResult> DownloadFiles(DownLoadModel input)
{
if (!Directory.Exists(input.pathUrl))
{
throw new UserFriendlyException("當(dāng)前要下載的文件夾不存在或已刪除");
}
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");//文件流方式,指定文件流對(duì)應(yīng)的ContenType。
}
public static class ZipHelper
{
/// <summary>
/// 壓縮文件
/// </summary>
/// <param name="sourceFilePath"></param>
/// <param name="destinationZipFilePath"></param>
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); // 壓縮級(jí)別 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)) //如果當(dāng)前是文件夾,遞歸
{
CreateZipFiles(file, zipStream, staticFile);
}
else //如果是文件,開(kāi)始?jí)嚎s
{
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方法傳入一個(gè)源文件的路徑,一個(gè)目標(biāo)文件的路徑,這里我的目標(biāo)文件設(shè)置在appsetting.json里是個(gè)臨時(shí)路徑,只為前端當(dāng)次下載使用。這樣我們就在后臺(tái)將數(shù)據(jù)以壓縮包的形式壓縮好,并返回?cái)?shù)據(jù)流給前端了。
1.2 vue 下載壓縮文件
<el-button
icon="el-icon-download"
size="mini"
type="primary"
class="pull-right"
@click="downloadFile"
>下載文件到本地</el-button>
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 對(duì)象
document.body.removeChild(elink);
} else {
// IE10+下載
navigator.msSaveBlob(blob, fileName);
}
this.loading = false;
});
},
之前下載Excel時(shí),我們傳入后端的content-type為"application/json;application/octet-stream",經(jīng)過(guò)測(cè)試發(fā)現(xiàn)壓縮文件不能使用這種content-type,所以我們?nèi)サ袅恕?br /> 另外就是const blob = new Blob([content], { type: "application/zip" });這行代碼,如果不加,雖然也能下載,但是下載后的壓縮包卻無(wú)法打開(kāi),提示壓縮不正確或壓縮包已損壞。
好了,到此壓縮文件的下載就完成了,由于我也是第一次遇到壓縮文件的下載,經(jīng)過(guò)摸索終于解決了問(wèn)題??雌饋?lái)也比較簡(jiǎn)單,你學(xué)會(huì)使用了嗎?
總結(jié)
到此這篇關(guān)于.netcore+vue 實(shí)現(xiàn)壓縮文件下載的文章就介紹到這了,更多相關(guān)vue 實(shí)現(xiàn)壓縮文件下載內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Vue引入路徑正確但一直報(bào)錯(cuò)問(wèn)題:Already included file name&n
這篇文章主要介紹了Vue引入路徑正確但一直報(bào)錯(cuò):Already included file name ‘××ב differs from file name ‘××ב only in casing.具有很好的參考價(jià)值,希望對(duì)大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2023-12-12
Vue enter回車導(dǎo)致頁(yè)面刷新問(wèn)題及解決
這篇文章主要介紹了Vue enter回車導(dǎo)致頁(yè)面刷新問(wèn)題及解決方案,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2022-10-10
vue操作動(dòng)畫(huà)的記錄animate.css實(shí)例代碼
這篇文章主要介紹了vue操作動(dòng)畫(huà)的記錄animate.css的相關(guān)知識(shí),非常不錯(cuò),具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2019-04-04
vant?toast?關(guān)閉棧溢出問(wèn)題及解決
這篇文章主要介紹了vant?toast?關(guān)閉棧溢出問(wèn)題及解決,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2022-05-05
vue?beforeDestroy?clearInterval清除定時(shí)器失效的解決
這篇文章主要介紹了vue?beforeDestroy?clearInterval清除定時(shí)器失效的解決方案,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2023-06-06
vue如何使用formData傳遞文件類型的數(shù)據(jù)
這篇文章主要介紹了vue如何使用formData傳遞文件類型的數(shù)據(jù)問(wèn)題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2023-05-05

