我正在尝试使用NodeJs SDK从amazon S3下载jpg图像。我能够在后端获取文件对象。但是当我尝试创建一个blob对象并从angular下载它时,我无法打开该文件。当我尝试用任何图像编辑器打开它时,我得到一个错误,好像文件已损坏或格式不正确。
这是我的Node JS代码:
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);
});
}
});
角度代码:
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);
});
};
答案 0 :(得分:0)
我解决了这个问题。问题似乎与Uint8转换有关。
我添加了这些行,它运行良好:
.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});