Upload to S3 with AWS

30 Mar 2022

Upload files to S3 with AWS with JavaScript

#Create a Bucket

// Create a new S3 bucket for the new group.
        const client = new S3( { region: 'us-east-1' });
        const bucketParams = {
          Bucket: 'bucketname',
        }
        client.createBucket(bucketParams, function(err, data) {
          if (err) console.log(err, err.stack);
          else     console.log(data);
        });

#upload a file

with ACL public read

          // do upload
    const s3 = new S3();
    const uploadResult = await s3.upload( {
      Bucket: this.configService.get('AWS_PUBLIC_BUCKET_NAME'),
      Body: imageBuffer,
      Key: `${uuid()}-${originalName}`,
      ACL:'public-read',
    }).promise()

private file


  const {getSignedUrl} = require('@aws-sdk/s3-request-presigner');
  const {S3Client, PutObjectCommand, GetObjectCommand} = require('@aws-sdk/client-s3');

...

        const client = new S3Client( { region: 'us-east-1' });
        const bucketParams = {
                Bucket: bucket_name,
                Key: data.url,
                Body: image_buffer,
        };
        const command = new PutObjectCommand( bucketParams );
        client.send(command, function(err, data) {
                if( err ) {
                  console.log(err, data);
                }
        })

#delete a file

    const s3 = new S3();
    await s3.deleteObject({
      Bucket: this.configService.get('AWS_PUBLIC_BUCKET_NAME'),
      Key: upload.key,
    }).promise();

#presigned url


  const {getSignedUrl} = require('@aws-sdk/s3-request-presigner');
  const {S3Client, PutObjectCommand, GetObjectCommand} = require('@aws-sdk/client-s3');

...

        // Send a presigned URL for the requested image. 
        var bucket_name = 'somebucket'
        const client = new S3Client ( { region: 'us-east-1' });
        var params = {
          Bucket: bucket_name,
          Key: data.url,
          Expires: 600,
          ResponseContentType: 'image/png'};
        const command = new GetObjectCommand( params );
         getSignedUrl( client, command, { expiresIn: 600 }, {} ).then( ( presigned_url) => {
            data.presigned_url = presigned_url;
              var obj = create_image_obj(data);
              obj.image.meta = JSON.stringify(data.image_data, null, 2);
              return callback(null, obj);
        });