Tuesday, February 26, 2019

Nodejs upload file to S3 bucket and create signed url

AWS.config.update({
    region: 'region',
    accessKeyId: 'adadadada',
    secretAccessKey: 'aadadadadad'});

const s3 = new AWS.S3();
const today = new Date();
const token = 'test-upload';
return new Promise((resolve, reject) => {
    // console.log(req.files.inputFile);    
fs.readFile(req.files.inputFile.path, (err, fileBuffer) => {
        const params = {
            ACL: 'authenticated-read',            
            Bucket: 'dadadadadada',
            ContentType: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
            Key: `test-upload/${token}.xlsx`,
            Body: fileBuffer
        };
        s3.putObject(params, (perr) => {
            if (perr) {
                reject(perr);
            } else {
                const gsuparams = { Bucket: params.Bucket, Key: params.Key, Expires: 60 * 24};
                s3.getSignedUrl('getObject', gsuparams, (gsuerr, url) => {
                    if (gsuerr) {
                        reject(gsuerr);
                    } else {
                        resolve({
                            url: `${token}.xlsx`,
                            url2: url
                        });
                    }
                });
            }
        });
    });
});

Share/Bookmark

0 comments:

Post a Comment