简体   繁体   English

使用 AWS-SDK Nodejs 从 S3 下载图像会下载损坏的图像

[英]Downloading images from S3 with AWS-SDK Nodejs downloads a corrupt image

I'm trying to download images from aws s3 using the AWS-SDK for nodejs.我正在尝试使用适用于 nodejs 的 AWS-SDK 从 aws s3 下载图像。 The file does get downloaded and the size is also correct.该文件确实被下载并且大小也正确。 However, the file is corrupted and shows Decompression error in IDAT.但是,文件已损坏并在 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");
        });
    }

Here's the link I followed - https://docs.aws.amazon.com/sdk-for-javascript/v2/developer-guide/requests-using-stream-objects.html The file should get downloaded without any error.这是我遵循的链接 - https://docs.aws.amazon.com/sdk-for-javascript/v2/developer-guide/requests-using-stream-objects.html该文件应该可以毫无错误地下载。 I tried searching on stack and there are some similar questions, however, they are using nodejs to deliver the output to the frontend and those solutions aren't working for me.我尝试在堆栈上搜索并且有一些类似的问题,但是,他们使用 nodejs 将输出传送到前端,而这些解决方案对我不起作用。

It wasn't necessary to make a mess and do all this... It can directly be achieved by -没有必要弄得一团糟,做这一切……可以直接通过-

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.");
        });
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM