Giter Site home page Giter Site logo

ikhsanalatsary / multer-sharp-s3 Goto Github PK

View Code? Open in Web Editor NEW
54.0 4.0 34.0 1.17 MB

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

License: MIT License

JavaScript 2.80% TypeScript 97.20%
multer typescript sharp aws aws-s3 formdata

multer-sharp-s3's Introduction

multer-sharp-s3

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

DigitalOcean Referral 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

option default value role
S3 no object instance from AWS.S3 class. it mus be specify
Key randomString string or function your s3 Key
Bucket no string Required your bucket name on AWS S3 to upload. Environment variable - AWS_BUCKET
ACL 'public-read' string Required acl credentials file for AWS S3
multiple false boolean for multiple resize to work
resize no object or Array<object> when multiple is true. Note: suffix must be specify when using resize as Array size specification

Sharp options

Please visit this sharp for detailed overview of specific option.

multer sharp s3 embraces sharp options, as table below:

option default value role
resize undefined object for output image, as follow: { width?: 300, height?: 200, options?: {...resizeOptions} }. doc: sharpResizeOptions size specification
crop undefined crop image
background undefined set the background for the embed, flatten and extend operations.
embed undefined embed on canvas
max undefined set maximum output dimension
min undefined set minimum output dimension
withoutEnlargement undefined do not enlarge small images
ignoreAspectRatio undefined ignore aspect ration while resizing images
extract undefined extract specific part of image
trim undefined Trim boring pixels from all edges
flatten undefined Merge alpha transparency channel, if any, with background.
extend undefined Extends/pads the edges of the image with background.
negate undefined Produces the negative of the image.
rotate undefined Rotate the output image by either an explicit angle
flip undefined Flip the image about the vertical Y axis.
flop undefined Flop the image about the horizontal X axis.
blur undefined Mild blur of the output image
sharpen undefined Mild sharpen of the output image
gamma undefined Apply a gamma correction.
grayscale or greyscale undefined Convert to 8-bit greyscale; 256 shades of grey.
normalize or normalise undefined Enhance output image contrast by stretching its luminance to cover the full dynamic range.
withMetadata undefined Include all metadata (EXIF, XMP, IPTC) from the input image in the output image.
convolve undefined Convolve the image with the specified kernel.
threshold undefined Any pixel value greather than or equal to the threshold value will be set to 255, otherwise it will be set to 0
toColourspace or toColorspace undefined Set the output colourspace. By default output image will be web-friendly sRGB, with additional channels interpreted as alpha channels.
toFormat undefined '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: sharpToFormat type 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

multer-sharp-s3's People

Contributors

audaxion avatar dependabot[bot] avatar greenkeeper[bot] avatar ikhsanalatsary avatar jeetkn avatar snyk-bot avatar yek-plus avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar

multer-sharp-s3's Issues

Metadata and Content-Disposition

Will this library support Metadata and Content-Disposition?

I've tried adding Content-Disposition like this:

var upload = multer({
    storage: multerS3({
        s3: s3,
        Bucket: s3Bucket,
        ContentType: multerS3.AUTO_CONTENT_TYPE,
        ContentDisposition: 'attachment',
        Key: (req, file, cb) => {
            cb(null, file.originalname);
        }
    }),
    fileFilter: mediaFilter
});

but in my S3 bucket, the metadata Content-Disposition does not get added.

S3 Upload Property has Content-Disposition as one of its properties.

Looking forward to this.

Multiple files not working properly

Hi,

Thanks very much for creating this wonderful package.
I tried it with multiple sizes yesterday. It worked when the request has one file. When there are multiple files, it doesn't seem to work.

In router, I am using:

fileUploadResizeS3.fields([
	{ name: 'eventImage', maxCount: 1 },
	{ name: 'courseMap', maxCount: 1 }
]),

fileUploadResizeS3 is where I define multer-sharp-s3:

const fileUploadResizeS3 = multer({
	limits: 1500000, 
	storage: s3Storage({
		ACL: 'public-read', 
		s3: s3,
		Bucket: process.env.S3_BUCKET_NAME,
		metadata: (req, file, cb) => {
			const ext = MIME_TYPE_MAP[file.mimetype];
			cb(null, { fieldName: file.fieldname });
		},
		Key: (req, file, cb) => {
			const UUID = uuid();
			const ext = MIME_TYPE_MAP[file.mimetype];

			let S3Folder;
                          .........

			cb(null, S3Folder + '/' + UUID + '.jpg');
		},
		multiple: true,
		resize: [{ suffix: 'small', width: 300 }, { suffix: 'original' }],
		toFormat: { type: 'jpeg', options: { quality: 100 } }
	}),
	fileFilter: (req, file, cb) => {
		const isValid = !!MIME_TYPE_MAP[file.mimetype];
		let error = isValid ? null : new Error('Invalid MIME type!');
		cb(error, isValid);
	}
});

It did return 2 file arrays:

req.files =  [Object: null prototype] {
  eventImage: [
    {
      fieldname: 'eventImage',
      originalname: 'Bowser.jpg',
      encoding: '7bit',
      mimetype: 'image/jpeg',
      small: [Object],
      original: [Object]
    }
  ],
  courseMap: [
    {
      fieldname: 'courseMap',
      originalname: 'CourseMap.png',
      encoding: '7bit',
      mimetype: 'image/png',
      small: [Object],
      original: [Object]
    }
  ]
}

The problem is files inside of eventImage are actually coureMap files. CourseMap files are empty, 0 byte.

Please look into this issue and let me know if you need more information.

Thanks again!

Auto Rotating the Image

Hello I am using multer-sharp-s3 for upload and resize images on s3

but some how it's auto rotating some images

Can anyone help on this

`const upload = multer({
fileFilter: (req, file, cb) => {
console.log(file);

if (file.mimetype == "application/octet-stream"){
    file.mimetype = 'image/jpeg';
}
if (file.mimetype == "image/png" || file.mimetype == "image/jpg" || file.mimetype == "image/jpeg") {
  cb(null, true);
} else {
  req.file_error = "INVALID";
  cb(null,false);
  //cb('Only .png, .jpg and .jpeg format allowed!', false);
  //return cb(new Error('Only .png, .jpg and .jpeg format allowed!'));

}

},
storage: s3Storage({
s3: s3,
Bucket: process.env.S3_BUCKET_NAME,
Key: (req, file, cb) => {
let originalname = file.originalname;
var extension = originalname.substr(originalname.lastIndexOf('.') + 1);
crypto.pseudoRandomBytes(8, (err, raw) => {
cb(err, err ? undefined : "v2/poster/" + raw.toString("hex"))+'.'+extension;
});
},
ACL: process.env.S3_ACL,
multiple: true,
resize: [{ suffix: "landingDeck", width: 800,height: 600, fit: "fill" }],
//resize: [{suffix: 'landingDeck' }],
//cacheControl: "max-age=31536000",

}),
});
`

Unable to add metadata

Hi,

Thank you for making this library. It is super useful and I would like to use it for my app in production. I was wondering if it is possible to add metadata and content type to an image when uploading. As of now, I don't see them as options in your README.

I was able to set contentType by using multer-s3 library, but it would be nice if multer-sharp-s3 could have this feature too to avoid having to install both libs :)

Additionally, I tried adding metadata to an image but it doesn't seem to work. Here's the code I tried.

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

...

const storage = s3Storage({
  s3,
  Bucket: "bucket-name",
  contentType: multerS3.AUTO_CONTENT_TYPE,
  metadata: (req, file, cb) => {
    cb(null, { ...req.body });
  },
  Key: (req, file, cb) => {
    const currentTime = getCurrentTime();
    fileName = `${req.body.category}-${currentTime}-${file.originalname}`;
    cb(null, fileName);
  },
  resize: {
    width: 400,
    height: 400
  },
  max: true
});
const upload = multer({ storage });

...

Image is uploaded to S3 without added metadata. I tried capitalizing the metadata key to match your other keys' convention, but it gave me this error: InvalidParameterType: Expected params.Metadata to be a map.

{rotate: true} breaks my app

multersharps3

Hello, maybe I'm not using the rotate how I should be but in the previous version it worked just fine. Since 0.2.0 whenever I upload an image this happens. I took the liberty of going into the code and as I saw the part that is commented in transformer.js was responsible for things working. Maybe I'm totally off-point but I said to give you my observations since they may be of use to you.

Cheers

An in-range update of aws-sdk is breaking the build 🚨

The devDependency aws-sdk was updated from 2.442.0 to 2.443.0.

🚨 View failing branch.

This version is covered by your current version range and after updating it in your project the build failed.

aws-sdk is a devDependency of this project. It might not break your production code or affect downstream projects, but probably breaks your build or test tools, which may prevent deploying or publishing.

Status Details
  • ❌ continuous-integration/travis-ci/push: The Travis CI build could not complete due to an error (Details).

Release Notes for Release v2.443.0

See changelog for more information.

Commits

The new version differs by 1 commits.

See the full diff

FAQ and help

There is a collection of frequently asked questions. If those don’t help, you can always ask the humans behind Greenkeeper.


Your Greenkeeper Bot 🌴

An in-range update of @types/node is breaking the build 🚨

The devDependency @types/node was updated from 11.13.7 to 11.13.8.

🚨 View failing branch.

This version is covered by your current version range and after updating it in your project the build failed.

@types/node is a devDependency of this project. It might not break your production code or affect downstream projects, but probably breaks your build or test tools, which may prevent deploying or publishing.

Status Details
  • ❌ continuous-integration/travis-ci/push: The Travis CI build could not complete due to an error (Details).

FAQ and help

There is a collection of frequently asked questions. If those don’t help, you can always ask the humans behind Greenkeeper.


Your Greenkeeper Bot 🌴

Not able to upload multiple images

Hi,

This lib is very usefull, it would be good to have support to multiple uploads at once.

router.post('/update', isAuthorized, upload.array('images', 20), update);

const upload = multer({
storage: s3Storage({
s3,
ACL: 'public-read',
Bucket: config.awsBucket,
multiple: true,
crop: 'attention',
resize: [
{ suffix: 'xlg', width: 1200 },
{ suffix: 'lg', width: 800, height: 600 },
{ suffix: 'md', width: 500, height: 500 },
{ suffix: 'sm', width: 265, height: 190 },
{ suffix: 'xs', width: 100 },
],
Key(req, file, cb) {
cb(null, ${Buffer.from(file.originalname).toString('base64')}_${Date.now().toString()});
},
}),
});

Right now if I use this code to upload several images, the first one is uploaded successfully but the rest all are stored with 0 bites.

Not able to upload BMP format

When I'm trying to upload BMP file to S3, I'm facing the following error below.

Error: Input buffer contains unsupported image format

It seems like the multer package does not support BMP format. Do you have any ideas?

Rewrite Lib

Improve parallel programming using worker_threads or using worker_pool. I don't know it is possible or not in multer lib

[dependencies] Update sharp version

sharp version needs to be updated in order to support Node v12. Version in your dependencies causes compilation failure because Node v12 removed deprecated v8::Handle.

Keep .GIF/ .Webp animated

Hi guys,

I am having problem retaining animation when uploading images to s3. Could someone help me about this ?

Thank you.

Suffix on Resize problem

Thanks for amazing package, I have a little problem about suffix, i want to resize image to multiple size, this is my code :

Screen Shot 2021-09-28 at 11 48 34

the result what i got on S3 like this :

Screen Shot 2021-09-28 at 11 50 03

the problem is no type on my uploaded file, I've try add static extension on suffix like

{suffix : "1920px.jpg"}

it's work !, but i need extension with dynamic responsibility

I've to try use file.originamname for Key but the output something like :

Screen Shot 2021-09-28 at 11 53 26

suffix print after the extension

my expectation for output is "<filename>-<suffix>.<extension>" , How do I got this output ?

Thanks !

Memory leak detected.

Hi.
It seems that when uploading an image with multiple resizes causes memory leaks under a small load. I've performed a load test using this library and it fails around 15 concurrent requests. Here's the error stack. Any help would be appreciated.

MaxListenersExceededWarning: Possible EventEmitter memory leak detected. 11 error listeners added. Use emitter.setMaxListeners() to increase limit
at _addListener (events.js:247:17)
at Sharp.addListener (events.js:263:10)
at Sharp.Readable.on (_stream_readable.js:800:35)
at ManagedUpload.send (/Users/me/Documents/wip/project/node_modules/aws-sdk/lib/s3/managed_upload.js:185:11)
at /Users/me/Documents/wip/project/node_modules/aws-sdk/lib/util.js:798:25
at new WrappedPromise (/Users/me/Documents/wip/project/node_modules/async-listener/es6-wrapped-promise.js:13:18)
at ManagedUpload.promise (/Users/me/Documents/wip/project/node_modules/aws-sdk/lib/util.js:797:14)
at MergeMapSubscriber.sizes.pipe.operators_1.mergeMap [as project] (/Users/me/Documents/wip/project/node_modules/multer-sharp-s3/dist/main.js:113:52)
at MergeMapSubscriber._tryNext (/Users/me/Documents/wip/project/node_modules/rxjs/internal/operators/mergeMap.js:69:27)
at MergeMapSubscriber._next (/Users/me/Documents/wip/project/node_modules/rxjs/internal/operators/mergeMap.js:59:18)
at MergeMapSubscriber.Subscriber.next (/Users/me/Documents/wip/project/node_modules/rxjs/internal/Subscriber.js:66:18)
at MergeMapSubscriber.notifyNext (/Users/me/Documents/wip/project/node_modules/rxjs/internal/operators/mergeMap.js:92:26)
at InnerSubscriber._next (/Users/me/Documents/wip/project/node_modules/rxjs/internal/InnerSubscriber.js:28:21)
at InnerSubscriber.Subscriber.next (/Users/me/Documents/wip/project/node_modules/rxjs/internal/Subscriber.js:66:18)
at /Users/me/Documents/wip/project/node_modules/rxjs/internal/util/subscribeToPromise.js:7:24
at propagateAslWrapper (/Users/me/Documents/wip/project/node_modules/async-listener/index.js:504:23)
at /Users/me/Documents/wip/project/node_modules/async-listener/glue.js:188:31
at /Users/me/Documents/wip/project/node_modules/async-listener/index.js:541:70
at /Users/me/Documents/wip/project/node_modules/async-listener/glue.js:188:31

An in-range update of @types/jest is breaking the build 🚨

The devDependency @types/jest was updated from 24.0.11 to 24.0.12.

🚨 View failing branch.

This version is covered by your current version range and after updating it in your project the build failed.

@types/jest is a devDependency of this project. It might not break your production code or affect downstream projects, but probably breaks your build or test tools, which may prevent deploying or publishing.

Status Details
  • ❌ continuous-integration/travis-ci/push: The Travis CI build could not complete due to an error (Details).

FAQ and help

There is a collection of frequently asked questions. If those don’t help, you can always ask the humans behind Greenkeeper.


Your Greenkeeper Bot 🌴

Enable Sharp ARM 64 support

Need to update the version of Sharp, as it doesn't include prebuilt libraries for ARM 64 until version 0.30.0.
Sharp v0.30.1 is the latest as of today.

Reference: lovell/sharp#2938

I could submit a PR if you'd like; should just be a package.json update for sharp to 0.30.1.

Thanks!

Fix sharp version in peerDependencies

The version in peerDependencies is 0.24.x, and the version in dependencies is 0.25.x. This is my fault - I forgot to fix this in #27

Thanks.

I don't believe the version in @types/sharp has been updated yet.

nodejs 10.15.1 not supporting

Not able to install in node version of 10.15.1 we can't change nodejs version for our product can can multer-s3-sharp support node js 10.15.1 version

When I Pass directory Attribute it will not upload in that directory

My Code:
const storage = s3Storage({
// Key: (req, file, cb) => {
// crypto.pseudoRandomBytes(16, (err, raw) => {
// cb(err, err ? undefined : raw.toString('hex'))
// })
// },
s3,
Bucket: bucketName,
acl: acl,
metadata: metaData,
multiple: true,
resize: [
{ suffix: 'xlg', directory: 'product/extralarge', width: 1200, height: 1200 },
{ suffix: 'lg', directory: 'product/large', width: 800, height: 800 },
{ suffix: 'md', directory: 'product/medium', width: 500, height: 500 },
{ suffix: 'sm', directory: 'product/small', width: 300, height: 300 },
{ suffix: 'xs', directory: 'product/xtrasmall', width: 100 },
{ suffix: 'original', directory: 'product/original' }
],
});

It just stores as
bucket/filename-xs.jpg
not as bucket/product/xs/filename.jpg

My response:
{
"images": {
"fieldname": "file",
"originalname": "1(1).jpg",
"encoding": "7bit",
"mimetype": "image/jpeg",
"xs": {
"ACL": "public-read",
"ETag": ""2f8701ed2c65e6ae4ec68705c3bbbba2"",
"Location": "Bucket/6d90e0c93ccd5a31234f25c58dba4915-xs",
"key": "6d90e0c93ccd5a31234f25c58dba4915-xs",
"Key": "6d90e0c93ccd5a31234f25c58dba4915-xs",
"Bucket": "lumier32",
"directory": "xtrasmall",
"width": 100,
"height": 100,
"premultiplied": false,
"size": 3375,
"ContentType": "jpeg"
},
"sm": {
"ACL": "public-read",
"ETag": ""003a633ae136ad767df1b661431418c2"",
"Location": "Bucket/6d90e0c93ccd5a31234f25c58dba4915-sm",
"key": "6d90e0c93ccd5a31234f25c58dba4915-sm",
"Key": "6d90e0c93ccd5a31234f25c58dba4915-sm",
"Bucket": "lumier32",
"directory": "small",
"width": 300,
"height": 300,
"premultiplied": false,
"size": 17346,
"ContentType": "jpeg"
},
"md": {
"ACL": "public-read",
"ETag": ""2e8103cf1bec4e46012c30332138636e"",
"Location": "Bucket/6d90e0c93ccd5a31234f25c58dba4915-md",
"key": "6d90e0c93ccd5a31234f25c58dba4915-md",
"Key": "6d90e0c93ccd5a31234f25c58dba4915-md",
"Bucket": "lumier32",
"directory": "medium",
"width": 500,
"height": 500,
"premultiplied": false,
"size": 35310,
"ContentType": "jpeg"
},
"original": {
"ACL": "public-read",
"ETag": ""5055954117ccfe24edcea2ddb1ceef48"",
"Location": "Bucket/6d90e0c93ccd5a31234f25c58dba4915-original",
"key": "6d90e0c93ccd5a31234f25c58dba4915-original",
"Key": "6d90e0c93ccd5a31234f25c58dba4915-original",
"Bucket": "lumier32",
"directory": "original",
"width": 384,
"height": 384,
"premultiplied": false,
"size": 26063,
"ContentType": "jpeg"
},
"lg": {
"ACL": "public-read",
"ETag": ""30a0a0a80c7f6a76ace203bde3d337cd"",
"Location": "Bucket/6d90e0c93ccd5a31234f25c58dba4915-lg",
"key": "6d90e0c93ccd5a31234f25c58dba4915-lg",
"Key": "6d90e0c93ccd5a31234f25c58dba4915-lg",
"Bucket": "lumier32",
"directory": "large",
"width": 800,
"height": 800,
"premultiplied": false,
"size": 66100,
"ContentType": "jpeg"
},
"xlg": {
"ACL": "public-read",
"ETag": ""dd67b9a9d2c503772b6b84ba78789e25"",
"Location": "Bucket/6d90e0c93ccd5a31234f25c58dba4915-xlg",
"key": "6d90e0c93ccd5a31234f25c58dba4915-xlg",
"Key": "6d90e0c93ccd5a31234f25c58dba4915-xlg",
"Bucket": "lumier32",
"directory": "extralarge",
"width": 1200,
"height": 1200,
"premultiplied": false,
"size": 113850,
"ContentType": "jpeg"
}
},
"imageUrl": "Bucket/6d90e0c93ccd5a31234f25c58dba4915-xs",
"message": "Successfully uploaded!"
}

How to resize a image dynamically by passing a dynamic width

I am trying to set the resizing width from the database values
I have successfully developed the function with the Static Width. but doing it dynamic from the database is not possible

Can please guide about making the width value dynamic from the database using Helper function.

let partsImageResolution = Helper.getResolution();
const uploadS4 = multer({
    storage: s4Storage({
         s3: s3,
        ACL: 'public-read',
        Bucket: 'mxcdn/parts',
        contentType: s4Storage.AUTO_CONTENT_TYPE,
        Key: (req, file, cb) => {
            cb(null, Date.now() + '-' + file.originalname);
        },
        resize: partsImageResolution
    })
}).any();

Node.js multer-sharp-s3 working locally but error on Heroku: Error: Input buffer contains unsupported image format

I was able to run this locally with following code, but when I pushed it to Heroku, it gives below error.

Error: Input buffer contains unsupported image format

Code:

const aws = require('aws-sdk')
const { v4: uuidv4 } = require('uuid');

aws.config.update({
secretAccessKey: process.env.AWS_ACCESS_KEY,
accessKeyId: process.env.AWS_ACCESS_KEY_ID,
region: process.env.AWS_LOCATION,
})

const s3 = new aws.S3()

const s3Storage = require('multer-sharp-s3')
const MIME_TYPE_MAP = {
'image/png': 'png',
'image/jpeg': 'jpg',
'image/jpg': 'jpg',
}

const storage = s3Storage({
s3: s3,
Bucket: process.env.AWS_BUCKET_NAME,
Key: function(req, file, cb) {
console.log(file)
const isValid = MIME_TYPE_MAP[file.mimetype]
let error = new Error('Invalid mime type')
if (isValid) {
error = null
}
cb(error,${process.env.AWS_BUCKET_NAME}/places/${uuidv4()})
},
ACL: 'public-read',
multiple: true,
resize: {
width: 400,
height: 400,
},
})

const upload = multer({ storage })

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    πŸ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. πŸ“ŠπŸ“ˆπŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❀️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.