我的代码如下:
[System.Web.Mvc.HttpPost]
public ActionResult DownloaZipFile([FromBody] int id)
{
var result = _service.GetDocuments(id);
var downloadFileName = $"Report{id}.zip";
var downloadFilePath = Server.MapPath($"~/Uploads/TempZipDownload/{downloadFileName}");
if (System.IO.File.Exists(downloadFilePath))
{
System.IO.File.Delete(downloadFilePath);
}
var zip = ZipFile.Open(downloadFilePath, ZipArchiveMode.Create);
foreach (var file in result)
{
zip.CreateEntryFromFile(Server.MapPath(Path.Combine("~/Uploads/TempImageDownload/" + file.Filename)), file.Filename);
}
zip.Dispose();
return File(downloadFilePath, "application/zip", downloadFileName);
}
来自组件的 AngularJs 代码:
vm.downloadReport = function(id) {
service.DownloadReport(id).then(function(response) {
var file = new Blob([response.data],
{
type: 'application/zip'
});
if (navigator.msSaveBlob) {
navigator.msSaveBlob(file);
} else {
var fileUrl = URL.createObjectURL(file);
console.log(fileUrl);
var a = document.createElement('a');
a.href = fileUrl;
a.download = 'ReportDownload' + id + '.zip';
document.body.appendChild(a);
a.click();
}
});
}
毕竟代码它正在下载 zip 文件,但是当我试图打开 zip 文件时,它给了我错误。无效的 zip 文件。
请注意,我使用 System.IO.Compression 库来生成和下载 zip 文件。