Store files in S3 in the /tmp/ directory created by AWS Lambda

Store files in S3 in the /tmp/ directory created by AWS Lambda

Try to put a file saved under /tmp by Lambda to S3, and use /tmp as long as it is within the Lambda process.

const aws = require("aws-sdk");
const fs = require('fs');
const s3 = new aws.S3({'region':'us-east-2'});

exports.handler = (event, context, callback) => {
  const path = '/tmp/' + (new Date()).getTime() + '.txt'; // Timestamp.txt
  fs.writeFileSync(path, "aaaa", 'utf-8'); // Save under /tmp

  const config = {
    Bucket: "my-test-cc",
    Key: "sample.txt",
    ContentType: "text/comma-separated-values; charset=utf-8" // Save to S3 in CSV UTF-8
    // ACL: 'public-read-write', // Commented out but put
    Body: fs.readFileSync(path, 'utf-8') // Read from files under /tmp
  };

  s3.putObject(config, function(err, data) {
    if (err) {
      console.log(err);
      context.fail('upload failed.');
    }
    context.succeed('upload success.');
  });
};

A callback function is required because without a callback function for the putObject method, the process will end without creation.

You must also have permission to PUT to S3 via IAM. (FullAccess is fine if you just want to try it out.)

You can confirm that the file has been created.

AWS Lambdaで作成した/tmp/ディレクトリのファイルをS3にファイルを保存する

How to check Content-Type

Metadata was specified when saving to S3. This can be found in the properties of the S3 file.

Click on the file and click on the “Properties” tab.

AWS Lambdaで作成した/tmp/ディレクトリのファイルをS3にファイルを保存する

Next, click on “Metadata.

AWS Lambdaで作成した/tmp/ディレクトリのファイルをS3にファイルを保存する

You can see that Content-Type is specified for file uploads.

コメント

Discover more from 株式会社CONFRAGE ITソリューション事業部

Subscribe now to keep reading and get access to the full archive.

Continue reading

Copied title and URL