Facebook
From Ratul, 8 Months ago, written in JavaScript.
Embed
Download Paste or View Raw
Hits: 253
  1. router.post(
  2.     '/image',
  3.     authenticate,
  4.     multer({
  5.       storage: multerS3({
  6.         s3,
  7.         metadata(req, file, cb) {
  8.           cb(null, {
  9.             originalname: file.originalname,
  10.           });
  11.         },
  12.         bucket: `${process.env.DO_BUCKET}/somoy-backend-api-blob/images`,
  13.         contentType: multerS3.AUTO_CONTENT_TYPE,
  14.         acl: 'public-read',
  15.         key(req, file, cb) {
  16.           const extension = file.originalname.split('.').pop();
  17.  
  18.           if (!imageFormats.includes(extension)) {
  19.             const err = new Error('Invalid Image Format');
  20.             err.status = 400;
  21.             throw err;
  22.           }
  23.  
  24.           const filename = `${crypto.randomBytes(24).toString('hex')}.${extension}`;
  25.           cb(null, filename);
  26.         },
  27.       }),
  28.     }).array('images'),
  29.     async (req, res, next) => {
  30.       // const imageTags = req.body.tags.length > 0 ? req.body.tags.split(',') : [];
  31.       if (req.files.length > 0) {
  32.         req.files.forEach((file, i) => {
  33.           req.files[i].location = `${process.env.CLOUDFRONT_IMAGE_URL}/${file.key}`;
  34.           // req.files[i].tags = imageTags;
  35.         });
  36.         // await Image.insertMany(req.files);
  37.       }
  38.       try {
  39.         res.status(200).json({
  40.           status: 'success',
  41.           message: 'Files Uploaded!',
  42.           data: {
  43.             images: req.files,
  44.           },
  45.         });
  46.       } catch (err) {
  47.         next(err);
  48.       }
  49.     },
  50.   );