Utkarsh Raj
Utkarsh Raj

Reputation: 55

I want to upload files with extension to aws s3 but it will not upload file with extension

This is my File Upload.js but when i upload file it will get uploaded succesfully but its extension is missing i want to upload file with extension .Please help me

const aws = require('aws-sdk');
const multer = require('multer');
const multerS3 = require('multer-s3');
aws.config.update({
    secretAccessKey: '', 
    accessKeyId: '',  
    region: 'us-east-2'
});

const s3 = new aws.S3({ })

const fileFilter = (req, file, cb) => {
    if (file.mimetype === 'music/AAC' || file.mimetype === 'music/AVI' ||file.mimetype === 'music/mp3' ||file.mimetype === 'music/AVI') {
        cb(null, true)
    } else {
        cb(new Error('Invalid Mime Type, only JPEG and PNG'), false);
    }
  }

const upload = multer({

    storage: multerS3({
    fileFilter,
      s3,
      bucket: 'admin-song',
      acl: 'public-read',
      metadata: function (req, file, cb) {
        cb(null, {fieldName: 'TESTING_META_DATA!'});
      },
      key: function (req, file, cb) {
        cb(null, Date.now().toString())
      }
    })
  })

module.exports = upload;

And This is my Api End Point Guide Me Please

 app.post('/v1/admin/upload/song',function(req, res) {

        singleUpload(req, res, function(err) {

          if (err) {
            return res.status(422).send({errors: [{title: 'File Upload Error', detail: err.message}] });
          }
          console.log(res)
          return res.json({'imageUrl': req['file'].location});
        });
      });

Upvotes: 2

Views: 2734

Answers (1)

Prashanth S.
Prashanth S.

Reputation: 420

You have to add whatever string you want as filename in your multer function.You can add file extension to the file with the following method

const upload = multer({

    storage: multerS3({
    fileFilter,
      s3,
      bucket: 'admin-song',
      acl: 'public-read',
      metadata: function (req, file, cb) {
        cb(null, {fieldName: 'TESTING_META_DATA!'});
      },
      key: function (req, file, cb) {
        cb(null, Date.now().toString() + '.' + fileExtension)
      }
    })
  })

Upvotes: 4

Related Questions