anacronw / multer-s3

multer storage engine for amazon s3
MIT License
660 stars 190 forks source link

File Name #80

Closed AnirbanKundu closed 7 years ago

AnirbanKundu commented 7 years ago

I have the following code to save Files in S3. Following code I have

var express = require('express'),
    aws = require('aws-sdk'),
    bodyParser = require('body-parser'),
    multer = require('multer'),
    multerS3 = require('multer-s3');

aws.config.update({
    secretAccessKey: 'XXXXXXXXXX',
    accessKeyId: 'XXXXXXXXXX'
});

var app = express(),
    s3 = new aws.S3();

app.use(bodyParser.json());

var upload = multer({
    storage: multerS3({
        s3: s3,
        bucket: 'XXXXXXX',
        key: function (req, file, cb) {
            console.log(file);
            cb(null, Date.now()+file.originalname); 
        }
    })
});
app.post('/upload', upload.any(), function (req, res, next) {
    // Here I want to get the File Name
     res.send("Uploaded!");
 });

I want to get the FileName/KEY at the method level once the Upload is successful. I would be saving the files with Unique IDs. Once Saved, I will be saving the KEY in a Relational DB to keep a track of the Files. How can I get the file name [Date.now()+file.originalname]

AnirbanKundu commented 7 years ago

I found out , the Key is now a part of the response object

gadagal commented 6 years ago

Hi, I know it's a bit late, but just saw your question and answer here after encountering same challenge. I want to clarify the answer a little more. The filename, key, location, etag etc. can be accessed via req inside the router like this;

app.post('/upload', upload.any(), function (req, res, next) {
    console.log(req.files)
    // OUTPUT LIKE
//[ { fieldname: 'upl',
//    originalname: 'originalName.png',
//    encoding: '7bit',
//    mimetype: 'image/png',
//    size: 3186,
//    bucket: 'YOUR_S3_BUCKET',
//    key: 'newlyGeneratedKey.png',
//    acl: 'public-read',
//    contentType: 'application/octet-stream',
//    contentDisposition: null,
//    storageClass: 'STANDARD',
//    serverSideEncryption: null,
//    metadata: null,
//    location: //'https://YOUR_UNIQUE_BUCKET_IDENTIFIER.s3.amazonaws.com/newlyGeneratedKey.png',
//    etag: '"ETAG"' } ]
     res.send("Uploaded!");
 });