Reputation: 3452
I´m trying to download an jpg image from amazon S3 using the NodeJs SDK. I´m able to get the file object on the backend. However when I try to create a blob object and download it from angular, I cannot open the file. When I try to open it with any image editor I get an error as if the file is damaged or incorrectly formatted.
Here´s my Node JS code:
function downloadFile(file,callback) {
//Arranging file name
var fileKey = file.lifeCycle + "/" + file.id + "." + file.extension;
// download the file via aws s3 here
console.log('Trying to download file', file.id);
var AWS = require('aws-sdk');
var s3 = new AWS.S3();
var s3Params = {
Bucket: 'myBucket',
Key: fileKey
};
/*
res.attachment(fileKey);
var fileStream = s3.getObject(s3Params).createReadStream();
fileStream.pipe(res);
*/
s3.getObject(s3Params, function (err, data) {
if (err === null) {
res.send(data);
} else {
res.status(500).send(err);
}
callback(null);
});
}
});
The angular code:
vm.fileData = new ApiDownloadFile({fileId: 1});
vm.downloadFile = function(){
console.log("Downloading...");
vm.fileData.$query()
.then(function(response){
$log.log(response);
window.BlobBuilder = window.BlobBuilder ||
window.WebKitBlobBuilder ||
window.MozBlobBuilder ||
window.MSBlobBuilder;
console.dir(response.headers);
var blob = new Blob(response.Body.data,{type:response['content-type']});
var link = document.createElement('a');
link.href = window.URL.createObjectURL(blob);
link.download = "1.jpg";
link.click();
},function(err){
$log.log(err);
});
};
Upvotes: 1
Views: 1718
Reputation: 3452
I solved the problem. The issue seemed to be with the Uint8 conversion.
I added this lines and it worked fine:
.then(function(response) {
try{
$log.log(response);
var arrayBufferView = new Uint8Array(response.Body.data); // Convert the response to fix the problem of opening the file
$log.log(arrayBufferView);
var file = new Blob( [arrayBufferView], {type: response.ContentType});
Upvotes: 2