MERN and Amazon-s3 for file upload

317 Views Asked by At

How to post a file to Amazon S3 using node and react and save it path to mongoDB. with mongoose and formidable.

1

There are 1 best solutions below

0
On
private async storeFile(file: { buffer: Buffer, fileId: string }): Promise<string> {
    try {
      const awsConfig = new AWS.Config(storageConfig);
      const s3 = new AWS.S3(awsConfig);
      let storageLink = undefined;
      fs.readFile(file.buffer, (err, data) => {
        if (err) {
          throw err;
        }
        const params = {
          Bucket:storageConfig.s3Bucket,
          Key: `${storageConfig.s3Prefix}${file.fileId}`,
          Body: data,
        };
    
        s3.upload(params, (s3Err: Error, s3Data: AWS.S3.ManagedUpload.SendData) => {
          if (s3Err) {
            throw s3Err;
          }
          storageLink = s3Data.Location;
        });
      });
    
      return storageLink;
    
    } catch (error) {
      throw error;
    }
}

In your Service file where you wanna call this function, update with record in collection

const storageLink = this.storeFile({ buffer, fileId });
 const file = await file.updateOne({ _id: fileId }, {
    status: fileStatus.UPLOADED, // just a flag 
    fileId: storageLink,
});