Copy file from one AWS S3 Bucket to another bucket

2020-04-11 13:41发布

I am trying to copy a file from a AWS S3 bucket to another bucket using Node. The problem is if the file name doesn't has the white space for example: "abc.csv", It is working fine. But in case the file to which I want to copy has the white space in the file name for example: "abc xyz.csv". It is throwing the below error.

"The specified key does not exist." "NoSuchKey: The specified key does not exist. at Request.extractError (d:\Projects\Other\testproject\s3filetoarchieve\node_modules\aws-sdk\lib\services\s3.js:577:35)

Below is the code provided.

return Promise.each( files, file => {
        var params = {
            Bucket: process.env.CR_S3_BUCKET_NAME, 
            CopySource: `/${ process.env.CR_S3_BUCKET_NAME }/${ prefix }${ file.name}`, 
            Key: `${ archieveFolder }${ file.name }`
        };
        console.log(params);
        return new Promise(( resolve, reject) => {
            s3bucket.copyObject(params, function(err, data) {
                if (err){
                    console.log(err, err.stack); 
                    debugger
                } else {
                    console.log(data); 
                    debugger
                }             
            });
        });
    }).then( result => {
        debugger
    });

Early help would be highly appreciable. Thank you.

1条回答
够拽才男人
2楼-- · 2020-04-11 13:59

I think the problem is exactly that space in the filename.

S3 keys must be url encoded, as they need to be accesible in URL form. There are some packages that helps you with url formatting like speakingUrl or you can try writting some on your own, maybe just simply replacing spaces (\s) with dashes (_ or -) if you want to keep it friendly.

If you don't mind about that, you can simply encodeURIComponent(file.name)

Hope it helps!

查看更多
登录 后发表回答