Huge News!Announcing our $40M Series B led by Abstract Ventures.Learn More
Socket
Sign inDemoInstall
Socket

multer-sharp-s3

Package Overview
Dependencies
Maintainers
1
Versions
7
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

multer-sharp-s3

A plugin multer to transform image and upload to AWS S3

  • 0.2.5
  • latest
  • Source
  • npm
  • Socket score

Version published
Weekly downloads
1.1K
decreased by-23.17%
Maintainers
1
Weekly downloads
 
Created
Source

multer-sharp-s3

Build Status codecov.io Depedencies Status devDepedencies Status npm Greenkeeper badge


Multer Sharp S3 is streaming multer storage engine permit to transform / resize the image and upload to AWS S3.

This project is mostly an integration piece for existing code samples from Multer's storage engine documentation. With add-ons include AWS S3 and sharp

Minimum Requirement:

Node v12.13.0, npm v6+

Installation

npm:

npm install --save aws-sdk multer-sharp-s3

yarn:

yarn add aws-sdk multer-sharp-s3

Tests

Change aws configuration in your local.

yarn test

Importing

NodeJS

const s3Storage = require('multer-sharp-s3');

const storage = s3Storage(options);

TypeScript

import * as s3Storage from 'multer-sharp-s3';

const storage = s3Storage(options);

Usage

const express = require('express');
const multer = require('multer');
const s3Storage = require('multer-sharp-s3');
const aws = require('aws-sdk');

aws.config.update({
  secretAccessKey: config.uploads.aws.secretAccessKey, // Not working key, Your SECRET ACCESS KEY from AWS should go here, never share it!!!
  accessKeyId: config.uploads.aws.accessKeyId, // Not working key, Your ACCESS KEY ID from AWS should go here, never share it!!!
  region: config.uploads.aws.region, // region of your bucket
})

const s3 = new aws.S3()
const app = express();

// without resize image
const storage = s3Storage({
  s3,
  Bucket: config.uploads.aws.Bucket,
  Key: `${config.uploads.aws.Bucket}/test/${Date.now()}-myImage`,
  ACL: config.uploads.aws.ACL,
})
const upload = multer({ storage: storage })

app.post('/upload', upload.single('myPic'), (req, res) => {
    console.log(req.file); // Print upload details
    res.send('Successfully uploaded!');
});

// or

// single resize without Key
const storage2 = gcsSharp({
  s3,
  Bucket: config.uploads.aws.Bucket,
  ACL: config.uploads.aws.ACL,
  resize: {
    width: 400,
    height: 400
  },
  max: true
});
const upload2 = multer({ storage: storage2 });

app.post('/uploadandresize', upload2.single('myPic'), (req, res, next) => {
    console.log(req.file); // Print upload details
    res.send('Successfully uploaded!');
});

/* If you need generate image with specific size
 * simply to adding `multiple: true` property and
 * resize must be an `array` and must be include `suffix` property
 * and suffix has a special value that is 'original'
 * it will no transform image, just upload the image as is
 * example below with `Key` as callback function
 */
const storage = s3Storage({
  Key: (req, file, cb) => {
    crypto.pseudoRandomBytes(16, (err, raw) => {
      cb(err, err ? undefined : raw.toString('hex'))
    })
  },
  s3,
  Bucket: config.uploads.aws.Bucket,
  multiple: true,
  resize: [
    { suffix: 'xlg', width: 1200, height: 1200 },
    { suffix: 'lg', width: 800, height: 800 },
    { suffix: 'md', width: 500, height: 500 },
    { suffix: 'sm', width: 300, height: 300 },
    { suffix: 'xs', width: 100 },
    { suffix: 'original' }
  ],
});
const upload = multer({ storage });

app.post('/uploadmultiplesize', upload.single('myPic'), (req, res, next) => {
    console.log(req.file); // print output
    res.send('Successfully uploaded!');
});

/* 
 *  If the directory property exists, 
 *  the suffix property is ignored and 
 *  inserted separated by Bucket's directory.
 */
const storage3 = s3Storage({
  Key: (req, file, cb) => {
    crypto.pseudoRandomBytes(16, (err, raw) => {
      cb(err, err ? undefined : raw.toString('hex'))
    })
  },
  s3,
  Bucket: config.uploads.aws.Bucket,
  multiple: true,
  resize: [
    { suffix: 'lg', directory: 'large', width: 800, height: 800 },  // insert BUCKET/large/filename
    { suffix: 'md', directory: 'medium', width: 500, height: 500 }, // insert BUCKET/medium/filename
    { suffix: 'sm', directory: 'small', width: 300, height: 300 },  // insert BUCKET/small/filename
  ],
});
const upload3 = multer({ storage3 });

app.post('/uploadmultiplesize', upload3.single('myPic'), (req, res, next) => {
    console.log(req.file); // print output
    res.send('Successfully uploaded!');
});

// also can upload any file (non image type)
const storage = s3Storage({
  s3,
  Bucket: config.uploads.aws.Bucket,
  Key: `${config.uploads.aws.Bucket}/test/${Date.now()}-myFile`,
  ACL: config.uploads.aws.ACL,
  // resize or any sharp options will ignore when uploading non image file type
  resize: {
    width: 400,
    height: 400,
  },
})
const upload = multer({ storage })

app.post('/uploadfile', upload.single('myFile'), (req, res, next) => {
    console.log(req.file); // print output
    res.send('Successfully uploaded!');
});

for more example you can see here

Multer-Sharp-S3 options

multer sharp s3 is inherit from s3 upload property putObjectRequest. Below are special / custom options from this package

optiondefaultvaluerole
S3noobjectinstance from AWS.S3 class. it mus be specify
KeyrandomStringstring or functionyour s3 Key
BucketnostringRequired your bucket name on AWS S3 to upload. Environment variable - AWS_BUCKET
ACL'public-read'stringRequired acl credentials file for AWS S3
multiplefalsebooleanfor multiple resize to work
resizenoobject or Array<object> when multiple is true. Note: suffix must be specify when using resize as Arraysize specification
Sharp options

Please visit this sharp for detailed overview of specific option.

multer sharp s3 embraces sharp options, as table below:

optiondefaultvaluerole
resizeundefinedobject for output image, as follow: { width?: 300, height?: 200, options?: {...resizeOptions} }. doc: sharpResizeOptionssize specification
cropundefinedcrop image
backgroundundefinedset the background for the embed, flatten and extend operations.
embedundefinedembed on canvas
maxundefinedset maximum output dimension
minundefinedset minimum output dimension
withoutEnlargementundefineddo not enlarge small images
ignoreAspectRatioundefinedignore aspect ration while resizing images
extractundefinedextract specific part of image
trimundefinedTrim boring pixels from all edges
flattenundefinedMerge alpha transparency channel, if any, with background.
extendundefinedExtends/pads the edges of the image with background.
negateundefinedProduces the negative of the image.
rotateundefinedRotate the output image by either an explicit angle
flipundefinedFlip the image about the vertical Y axis.
flopundefinedFlop the image about the horizontal X axis.
blurundefinedMild blur of the output image
sharpenundefinedMild sharpen of the output image
gammaundefinedApply a gamma correction.
grayscale or greyscaleundefinedConvert to 8-bit greyscale; 256 shades of grey.
normalize or normaliseundefinedEnhance output image contrast by stretching its luminance to cover the full dynamic range.
withMetadataundefinedInclude all metadata (EXIF, XMP, IPTC) from the input image in the output image.
convolveundefinedConvolve the image with the specified kernel.
thresholdundefinedAny pixel value greather than or equal to the threshold value will be set to 255, otherwise it will be set to 0
toColourspace or toColorspaceundefinedSet the output colourspace. By default output image will be web-friendly sRGB, with additional channels interpreted as alpha channels.
toFormatundefined'jpeg', 'png', 'magick', 'webp', 'tiff', 'openslide', 'dz', 'ppm', 'fits', 'gif', 'svg', 'pdf', 'v', 'raw' or object. if object specify as follow: { type: 'png', options: { ...toFormatOptions } } doc: sharpToFormattype of output file to produce.

NOTE Some of the contents in the above table maybe is not be updated, you can check more here


Why

Because We need to transform an image using sharp and upload it to AWS S3 using multer middleware at once. Build on top with TypeScript and reactive using RxJS as helper library in this package.

Mantra

refer to: intro rx

License

MIT Copyright (c) 2017 - forever Abdul Fattah Ikhsan

Keywords

FAQs

Package last updated on 16 Feb 2022

Did you know?

Socket

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc