Zip文件的下载
C# https://learn.microsoft.com/zh-cn/dotnet/api/system.io.compression.zipfile?view=net-7.0
(1)生成压缩文件,返回文件流给前端
1 public static byte[] ZipFiles(List<FileModel> filePathList, string zipDir) 2 { 3 string zipPath = $"{zipDir}.zip"; 4 if (File.Exists(zipDir)) 5 { 6 Directory.Delete(zipDir); 7 } 8 if (File.Exists(zipPath)) 9 { 10 File.Delete(zipPath); 11 } 12 13 Directory.CreateDirectory(zipDir); 14 ZipFile.CreateFromDirectory(zipDir, zipPath); 15 16 using (FileStream zipToOpen = new FileStream(zipPath, FileMode.Open)) 17 { 18 using (ZipArchive archive = new ZipArchive(zipToOpen, ZipArchiveMode.Update)) 19 { 20 foreach (FileModel file in filePathList) 21 { 22 archive.CreateEntryFromFile(file.FileUrl, file.FileName); 23 } 24 } 25 } 26 27 var buffer = File.ReadAllBytes(zipPath); 28 29 Directory.Delete(zipDir); 30 File.Delete(zipPath); 31 return buffer; 32 }
1 2 //安装包 DotNetZip 可以给文件加密 3 using Ionic.Zip; 4 5 using (ZipFile zip = new ZipFile()) 6 { 7 var addFile = @"44.jpg"; 8 zip.AddFile(addFile, "4455.jpg"); // no password for this one 9 zip.Password= "123456!"; 10 zip.AddFile("7440-N49th.png"); 11 zip.Password= "!Secret1"; 12 zip.AddFile("2005_Annual_Report.pdf"); 13 14 zip.Save("Backup.zip"); 15 }
1 [HttpGet("download")] 2 public async Task<ActionResult> DownloadFileAsync(long? fileId) 3 { 4 var buffer = await _fileManager.DownloadFileAsync(ticketId); 5 return new FileContentResult(buffer, "application/octet-stream"); 6 }
(2)前端接收文件流
1 import { downloadZip } from "@/assets/js/utils"; 2 downloadTicketFiles(id){ 3 this.$axios.get(`/api/ticketFile/download?ticketId=${id}`,{ responseType: "blob"}).then(res => { 4 if(res.data && res.data.length == 0){ 5 this.$message.warning('没有附件可以下载'); 6 return false; 7 } 8 downloadZip(res.data, 'TicketFiles.zip'); 9 10 }); 11 } 12 13 //封装的utils.js代码 14 export function downloadZip(data, name = '下载.zip') { 15 let blob = new Blob([data], { type: 'application/zip;charset=UTF-8' }); 16 let url = window.URL.createObjectURL(blob); 17 let aLink = document.createElement('a'); 18 aLink.style.display = 'none'; 19 aLink.setAttribute('href', url); 20 aLink.setAttribute('download', name); 21 document.body.appendChild(aLink); 22 aLink.click(); 23 document.body.removeChild(aLink); 24 window.URL.revokeObjectURL(url); 25 }
如果下载其他的文件,比如Excel把type 更换 type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=UTF-8'
csv type: 'application/csv;charset=UTF-8'
html type: 'application/html;charset=UTF-8'
对于编程的技术和问题,需要熟练技术,需要总结问题,更需要举一反三的思索。哈哈,Me是一个元气满满的妹子~~

浙公网安备 33010602011771号