Контроллер API на стороне сервера
Код: Выделить всё
public async Task DownloadZIP([FromBody] List req)
{
List pathLists = new List();
// From the req getting the file paths
pathLists.Add(filePath);
try
{
// if pathLists null, return from there
Stream streamZip = await Task.Run(() => someServer.ConvertToZIP(pathLists));
return File(streamZip, "application/zip", "file_name.zip");
}
catch (Exception ex)
{
// Handle exception and return
}
}
Код: Выделить всё
public Stream ConvertToZIP (List pathList)
{
var memoryStream = new MemoryStream();
using (ZipArchive zipArchive = new ZipArchive(memoryStream, ZipArchiveMode.Create, true))
{
pathList.ForEach(filePath =>
{
string fileName = Path.GetFileName(filePath);
var demoFile = zipArchive.CreateEntry(fileName);
var stream = CreateStream(filePath, FileMode.Open);
var reader = new StreamReader(stream);
var entryStream = demoFile.Open();
using (var streamWriter = new StreamWriter(entryStream))
{
streamWriter.Write(reader.ReadToEnd());
}
});
}
memoryStream.Position = 0;
return memoryStream;
}
Код: Выделить всё
downloadZIPFile()
{
someService.DownloadZIP(this.createList()).subscribe(res => {
if (res) {
var binaryData = [];
binaryData.push(res);
var url= window.URL.createObjectURL(new Blob(binaryData, {type: "application/zip"}));
var link = document.createElement('a');
link.href = url;
link.download = "filename.zip";
link.click();a
}
});
}
Код: Выделить всё
DownloadZIP(req: someEvents[]) : observable
{
let dowloadAPI = "someapi/some/some";
const httpOptions = {
responseType : 'blob' as 'json';
headers: new HttpHeaders({
// type as 'text/csv' also not worked
'Accept': 'application/vnd.ms-excel.sheet.macroEnabled.12'
})
};
return this.http.post(downloadAPI, req, httpOptions);
}
Подробнее здесь: https://stackoverflow.com/questions/787 ... -corrupted