📜  multer s3 - TypeScript (1)

📅  最后修改于: 2023-12-03 15:03:03.875000             🧑  作者: Mango

Multer S3 - TypeScript

Multer S3 is a middleware that provides a way to handle file uploads for Node.js applications. It works seamlessly with Amazon S3 to store the uploaded files, which can then be accessed later on. This tutorial will show you how to use Multer S3 with TypeScript.

Installation

To install Multer S3, simply use npm:

npm install @types/multer-s3 s3 multer --save

This will install both Multer S3 and the necessary dependencies.

Usage

To use Multer S3 in your TypeScript application, you need to create a new instance of the middleware:

import * as MulterS3 from 'multer-s3';
import * as AWS from 'aws-sdk';
import * as Multer from 'multer';

const s3 = new AWS.S3({
   // S3 configuration
});

const upload = Multer({
   storage: MulterS3({
      s3: s3,
      bucket: 'your-bucket',
      acl: 'public-read',
      contentType: MulterS3.AUTO_CONTENT_TYPE,
      metadata: function (req, file, cb) {
         cb(null, {originalName: file.originalname});
      },
      key: function (req, file, cb) {
         cb(null, 'uploads/' + Date.now().toString() + '-' + file.originalname);
      }
   })
});

The s3 object should be configured with your AWS access keys and your desired region.

The Multer middleware has been configured with the storage option that tells Multer to use Multer S3's storage engine. The bucket property specifies the S3 bucket where the uploaded files should be stored. If the acl property is specified, S3 will set the Access Control List on the uploaded file. The contentType property is used to set the content-type of the upload. The metadata function returns an object that will be used as metadata on the uploaded file. Finally, the key function is used to generate the name of the uploaded file in S3.

Conclusion

Multer S3 is a powerful middleware that allows for seamless file uploads to Amazon S3. By using TypeScript, you can ensure that your code is type-safe and performs as expected.