UNPKG

s3-upload-file

Version:

The **S3Uploader** class is a Node.js module designed to simplify the process of uploading files to Amazon S3. It utilizes the **AWS SDK**, **crypto**, **fs**, and **multer** libraries to provide a convenient interface for handling file uploads to an S3 b

106 lines (92 loc) 2.93 kB
const AWS = require('aws-sdk'); const { randomUUID } = require('crypto'); const fs = require('fs'); const multer = require('multer'); class S3Uploader { constructor(accessKeyId, secretAccessKey, region, bucketName) { this.s3 = new AWS.S3({ accessKeyId: accessKeyId, secretAccessKey: secretAccessKey, region: region, }); this.bucketName = bucketName; this.upload = multer({ dest: 'uploads/' }); } uploadMiddleware() { return this.upload.single('file'); } async uploadFile(req) { const fileStream = fs.createReadStream(req.path); let key = randomUUID(); console.log("key", this.bucketName); const uploadParams = { Bucket: this.bucketName, Key: `${key}`, Body: fileStream, ContentType: req.mimetype, }; return new Promise((resolve, reject) => { this.s3.upload(uploadParams, (err, data) => { if (err) { reject(err); } else { resolve(data.Location); } }); }); } } class S3PreSignedUrl { constructor(accessKeyId, secretAccessKey, region, bucketName, key) { this.s3 = new AWS.S3({ accessKeyId: accessKeyId, secretAccessKey: secretAccessKey, region: region, }); this.bucketName = bucketName; this.key = key this.expires = 36000; } async getSignedUrl() { const s3Params = { Bucket: this.bucketName, Key: this.key, Expires: this.expires, }; try { return new Promise((resolve, reject) => { this.s3.getSignedUrl('putObject', s3Params, (err, url) => { if (err) { reject(err); // Reject with the error received from AWS SDK } else { resolve(url); // Resolve with the signed URL } }); }); } catch (error) { throw new Error('Failed to generate signed URL: ' + error.message); } } // async uploadFile(req) { // const fileStream = fs.createReadStream(req.path); // let key = randomUUID(); // console.log("key", this.bucketName); // const uploadParams = { // Bucket: this.bucketName, // Key: `${key}`, // Body: fileStream, // ContentType: req.mimetype, // }; // return new Promise((resolve, reject) => { // this.s3.upload(uploadParams, (err, data) => { // if (err) { // reject(err); // } else { // resolve(data.Location); // } // }); // }); // } } // module.exports = { S3PreSignedUrl }; module.exports = { S3Uploader , S3PreSignedUrl};