I'm using the library SharpzipLib to create a zip file from files in a memory stream. The issue is that the generated zip seems to be corrupted and I can't open it.
MemoryStream outputMemStream = new MemoryStream();
ZipOutputStream zipStream = new ZipOutputStream(outputMemStream);
zipStream.SetLevel(3); //0-9, 9 being the highest level of compression
// loops through the PDFs I need to create
foreach (var file in files)
{
var newEntry = new ZipEntry(file.FileName);
newEntry.DateTime = DateTime.Now;
zipStream.PutNextEntry(newEntry);
byte[] bytes = file.Content;
MemoryStream inStream = new MemoryStream(bytes);
StreamUtils.Copy(inStream, zipStream, new byte[4096]);
inStream.Close();
zipStream.CloseEntry();
}
zipStream.IsStreamOwner = false; // False stops the Close also Closing the underlying stream.
zipStream.Close(); // Must finish the ZipOutputStream before using outputMemStream.
outputMemStream.Position = 0;
stream.Seek(0, SeekOrigin.Begin);
var httpResponseMessage = new HttpResponseMessage(HttpStatusCode.OK)
{
Content = new StreamContent(stream)
};
httpResponseMessage.Content.Headers.ContentType = new MediaTypeHeaderValue(contentType);
httpResponseMessage.Content.Headers.ContentLength = stream.Length;
httpResponseMessage.ContentDisposition =
new ContentDispositionHeaderValue(asAttachment ? DownloadAttachment : InlineAttachment)
{
FileName = fileName,
Name = fileCaption
};
Files contain a list of objects with a byte[] from a pdf and a name. If I download the files individually they are fine.
TargetfileName looks like this: testFile-2023-01-02-18-02-23.zip
I tried with asAttachement as true and false.
Here's how the file is downloaded on the front end :
var zipName = "TestFiles-" + new Date() + ".zip";
let viewModel = this.getViewModel(),
url = "localhost:10000/Documents/File?" + "ids=" + docIds.join(",") + "&fileName=" + zipName;
Ext.Ajax.request({
url: url,
method: 'GET',
useDefaultXhrHeader: false,
withCredentials: true,
success: function(response, options) {
if(response.status == 200) {
var a = document.createElement("a");
document.body.appendChild(a);
a.style = "display: none";
var blob = new Blob([response.responseBytes || response.responseXml || response.responseText], {type: 'octet/stream'});
var windowUrl = window.URL.createObjectURL(blob);
a.href = windowUrl;
a.download = zipName;
a.click();
}
}
});
It's ExtJS but I did a simple ajax request. I don't know if I did something wrong in the back-end or the front end.