Reputation: 1547
My front-end code (react) gets a response from my backend (node) and downloads a zip file as expected but the zip file, when clicked, will produce a CPGZ file instead instead of decompressing the zip.
React Code
downloadResultsFile() {
fetch(`https://XXXXXXXX/api/download-results-file?jobName=${this.props.selectedRun.jobs[0].env.MIC_JOB_ID}`, {
origin: 'same-origin',
})
.then((res) => res.blob())
.then((file) => FileSaver.saveAs(file, this.props.selectedRun.jobs[0].env.MIC_JOB_ID + '-results.zip'));
}
Node Code
downloadResults: function(app, s3){
app.use('/api', apiRoutes)
apiRoutes.get('/download-results-file', function(req, res, next){
res.set({'Content-type': 'text/plain'})
var params = {
Bucket: 'xxxxx',
Delimiter: '/',
Prefix: 'xxxxxx'
};
var filesArray = []
var files = s3.listObjectsV2(params).createReadStream()
var xml = new XmlStream(files)
xml.collect('Key')
xml.on('endElement: Key', function(item) {
filesArray.push(item['$text'].substr(params.Prefix.length))
})
var data = zip(filesArray, req.query.jobName, params)
xml.on('end', function() {
res.send(data.toString())
})
})
}
When I console.log(res)
on the front-end I get a "writeable stream" for an object. I convert that into a blob and then I use FileSaver to create the zip file. Any help will be greatly appreciated. Thank you!
Upvotes: 2
Views: 7671
Reputation: 4069
Your backend sends a zip file, not a text file. Don't use 'Content-type': 'text/plain'
, use 'Content-type': 'application/zip'
or 'Content-type': 'application/octet-stream'
instead.
What does zip(...)
returns ? I would expect a nodejs buffer. If so, res.send(data.toString())
will decode your content from UTF-8 (the default encoding). Since it's not a text but a binary content, you will corrupt your content here. Instead, use res.send(data)
.
Upvotes: 1