简体   繁体   中英

How can I upload files to S3 using multer without having multer store a copy of the files locally?

I am trying to upload files to S3 using an api that accepts multipart/form-data, without using multer the body is empty but after using it all is fine.
However, multer stores a copy of every file locally and this is not something I really want.
I do not really want to use multer-s3-v3 either, since I'm trying to send back the progress of the file using socket.io, which won't work if I use it.
Any idea on how to prevent multer from saving copies? or any other method I should use?

Here's my code:
The route

const multer  = require('multer')
const upload = multer({ dest: 'images/' });
router.post('/image-upload', upload.single('image'), authController.imageUpload);

The api

exports.imageUpload = async (req, res) => {
  const imagePath = req.file.path;
  console.log(imagePath);
  const blob = fs.readFileSync(imagePath);
  const uploadedImage = await s3
    .upload({
      Bucket: process.env.AWS_BUCKET,
      Key: `images/${req.file.originalname}`,
      Body: blob,
    }).on('httpUploadProgress', function(progress) {
      let progressPercentage = Math.round(progress.loaded / progress.total * 100);
      console.log(progressPercentage);
    })
    .promise();
  if (uploadedImage) {
    return res.status(200).send({
      message: "Image uploaded successfully",
      image: uploadedImage.Location.substring(36),
    });
  }
};

as you said "I do not really want to use multer-s3-v3 either, since I'm trying to send back the progress of the file using socket.io" then use cloudinary to store files easily and its kinda free do check this link https://cloudinary.com/blog/node_js_file_upload_to_a_local_server_or_to_the_cloud

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM