Reputation: 21
I have a problem downloading files. When I download the file, it turns out to be empty, I think that the problem is in the wrong headers, but I could not figure out what exactly.
I have a response body from controller
But I have empty response arraybuffer from component
And empty zip downloaded
What am I doing wrong?
request.component.ts
downloadZip() {
this.requestService.downloadZip(this.request.id)
.subscribe((res) => {
const blob = new Blob([res], { type: 'application/zip' });
saveAs(blob, 'Обращение №' + this.request.id + '.zip');
})
}
request.service.ts
downloadZip(requestId: number): Observable<any> {
return this.http.get(this.apiUrl + '/request/downloadZip?id=' + requestId, { responseType: 'arraybuffer'});
}
RequestController.cs
[HttpGet]
[Route("api/request/downloadZip")]
public async Task<IActionResult> DownloadZip(int id)
{
var stream = await _fileStoreService.GetRequestFilesZip(id);
Response.Body = stream;
Response.ContentType = "application/zip";
return Ok();
}
FileStoreService.cs
public async Task<MemoryStream> GetRequestFilesZip(int id)
{
var query = await _db.RequestMedia
.Where(_ => _.RequestId == id)
.ToListAsync();
var fileSharePath = Path.Combine(_configuration["FileTableRootPath"], "RequestFileStore");
var files = new List<string>();
foreach (var media in query)
files.Add(Path.Combine(fileSharePath, media.Hash + Path.GetExtension(WebUtility.HtmlDecode(media.Name))));
var memory = new MemoryStream();
ZipStrings.UseUnicode = true;
using(var zipStream = new ZipOutputStream(memory))
{
zipStream.SetLevel(3);
foreach(var file in files)
{
var entry = new ZipEntry(Path.GetFileName(file))
{
DateTime = DateTime.Now
};
zipStream.PutNextEntry(entry);
var inStream = new MemoryStream();
using var f = new FileStream(file, FileMode.Open, FileAccess.Read);
await f.CopyToAsync(inStream);
inStream.Close();
var content = inStream.ToArray();
await zipStream.WriteAsync(content.AsMemory(0, content.Length));
zipStream.CloseEntry();
}
zipStream.IsStreamOwner = false;
}
memory.Position = 0;
return memory;
}
Upvotes: 0
Views: 1194
Reputation: 21
I changed this
request.service.ts
downloadZip(requestId: number) {
return this.http.get(this.apiUrl + '/request/downloadZip?id=' + requestId, { responseType: 'blob'});
}
and this
RequestController.cs
[HttpGet]
[Route("api/request/downloadZip")]
public async Task<IActionResult> DownloadZip(int id)
{
var stream = await _fileStoreService.GetRequestFilesZip(id);
return new FileStreamResult(stream, "application/zip");
}
Everything works fine
Upvotes: 1