Sails.js File upload with Skipper to AWS S3
Asked Answered
B

2

7

I have a form where you can upload a file. I upload the file directly with skipper and it works perfectly.

req.file('file').upload({
    adapter: require('skipper-s3'),
    key: 'key',
    secret: 'secret',
    bucket: 'bucketname'
}, function (err, uploadedFiles) {
    if (err){
        // ko
    }
    else{
        // ok
    }
});

But I want to resize first and then upload the file, so:

sharp(original).resize(800).quality(90).toBuffer(function(err, outputBuffer) {
    if (err) {
        // ko
    }
    // ok
    outputBuffer;
 });

So, my question is: How can upload the outputBuffer instead of req.file('file') ?

Borak answered 11/11, 2014 at 14:47 Comment(1)
did you get solution for this problem?Manassas
M
3

Instead of using skipper-s3 you can use the aws-sdk module. Upload the image to disk (original), process it, upload it, and delete the original.

var AWS = require('aws-sdk'),
    fs = require('fs');

sharp(original).resize(800).quality(90).toBuffer(function(err, outputBuffer) {
    if (err) {
       ...
    } else {
        new AWS.S3({
            accessKeyId: 'your access key', 
            secretAccessKey: 'your secret',
            params : { 
                Bucket : 'your bucket',
                Key: 'desired filename'
            }
        });

        s3client.upload({ACL:'public-read', Body: outputBuffer}, function(err, result) {
            if(err) {
                //handle error
            } else {
               // continue, handle returned data
               fs.unlinkSync(original); // delete original
            }
        });
     }
 });

Alternatively, some libraries (like gm) can take a remote URL. You could use skipper-s3 to upload, then carry out the process above (where original is the s3 URL) and it would work, too—really not performant, at all, though.

Mejia answered 14/9, 2015 at 9:46 Comment(0)
L
1

Using Skipper-s3 and sails version_1 and sails-hook-uploads

npm i sails-hook-uploads

fn: async function (inputs) {
    var coverImage = await sails
      .uploadOne(inputs.coverImage, {
        // maxBytes: 3000000
        adapter: require('skipper-s3'),
        key: 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx',
        secret: 'xxxxxxxxxxxxxxxxxxxx',
        bucket: 'xxxxxxx',
        saveAs:'your custom file name ?',
        dirname: '/cover_images ?',
      })
      // Note: E_EXCEEDS_UPLOAD_LIMIT is the error code for exceeding
      // `maxBytes` for both skipper-disk and skipper-s3.
      .intercept('E_EXCEEDS_UPLOAD_LIMIT', 'tooBig')
      .intercept(
        (err) =>
          new Error('The coverImage upload failed: ' + util.inspect(err)),
      )

    if (!coverImage) {
      throw 'noFileAttached'
    }
}
Leavelle answered 11/5, 2020 at 23:48 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.