使用AWS-SDK Node.js从S3下载图像会下载损坏的图像

时间:2019-06-18 06:07:15

标签: javascript node.js aws-sdk-nodejs

我正在尝试使用适用于nodejs的AWS-SDK从AWS s3下载图像。 确实下载了文件,并且大小也正确。但是,该文件已损坏,并在IDAT中显示“解压缩”错误。

async download(accessKeyId, secretAccessKey, region, bucketName, baseImage) {
        console.log("Entered download");
        const s3 = new AWS.S3({region: region});
        const params = {
             Bucket: bucketName,
             Key: `base/${baseImage}`
         };

        const outStream = fs.createWriteStream(this.config.baseFolder + baseImage);
        const awsStream = s3.getObject(params, (uerr, data) => {
            if(uerr) throw uerr;
            console.log(`Base file downloaded successfully!`)
        }).createReadStream().pipe(outStream);

        awsStream.on('end', function() {
            console.log("successfully Downloaded");
        }).on('error', function() {
            console.log("Some error occured while downloading");
        });
    }

这是我关注的链接-https://docs.aws.amazon.com/sdk-for-javascript/v2/developer-guide/requests-using-stream-objects.html 该文件应该被下载而没有任何错误。我尝试在堆栈上搜索,但也有一些类似的问题,但是它们正在使用nodejs将输出传递到前端,而这些解决方案对我不起作用。

1 个答案:

答案 0 :(得分:0)

没有必要弄乱所有这些... 可以直接通过-

实现
async download(accessKeyId, secretAccessKey, region, bucketName, baseImage) {
        console.log("Starting Download... ")
        const s3 = new AWS.S3({
            accessKeyId: accessKeyId,
            secretAccessKey: secretAccessKey,
            region: region
        });
        const params = {
            Bucket: bucketName,
            Key: `base/${baseImage}`
         };

        s3.getObject(params, (err, data) => {
            if(err) console.error(err);
            console.log(this.config.baseFolder + baseImage);
            fs.writeFileSync(this.config.baseFolder + baseImage, data.Body);
            console.log("Image Downloaded.");
        });
    }