如何在Node.js中使用单个路由上传图像和视频到S3?

huangapple go评论145阅读模式
英文:

how can i upload images and video to s3 in one single route using nodejs

问题

这是我上传视频的方式:

router.post('/vid', upload.array('files', 5), async (req, res) => {
   try {
        const video = new Video();
        video.url = [];
        req.files.forEach((file) => {
          video.url.push(file.location);
        });
        const savedVideo = await video.save();
        res.json({
            message: '视频上传成功',
            video: savedVideo
        });
    } catch (error) {
       
    }
});

这是我上传图片的方式:

router.post('/products', upload.array("photos", 10), async (req, res) => {
  try {
    let product = new Product();
    product.photos.push(...req.files.map(({ location }) => location));
    await product.save();
  } catch (error) {
   
  }
});

这是我的中间件:

const aws = require("aws-sdk");
const multer = require("multer");
const multerS3 = require("multer-s3");

aws.config.update({
    secretAccessKey: process.env.AWSSecretKey,
    accessKeyId: process.env.AWSAccessKeyId,
    region: 'eu-north-1', // 更新为 'eu-north-1' 区域
    correctClockSkew: true
});

const s3 = new aws.S3();

const upload = multer({
    storage: multerS3({
        s3: s3,
        bucket: 'ajibs',
        acl: 'public-read',
        metadata: (req, file, cb) => {
            cb(null, { fieldName: file.fieldname });
        },
        key: (req, file, cb) => {
            cb(null, Date.now().toString())
        }
    })
})

module.exports = upload;

如果想在一个路由中同时上传图片和视频,可以使用以下方式:

router.post('/combined', upload.fields([{ name: 'photos', maxCount: 10 }, { name: 'files', maxCount: 5 }]), async (req, res) => {
   try {
        // 处理上传的图片和视频
        const video = new Video();
        const product = new Product();

        if (req.files['files']) {
          video.url = req.files['files'].map(file => file.location);
          await video.save();
        }

        if (req.files['photos']) {
          product.photos = req.files['photos'].map(file => file.location);
          await product.save();
        }

        res.json({
            message: '图片和视频上传成功',
            video: video,
            product: product
        });
    } catch (error) {
       
    }
});

这个路由使用了upload.fields来处理不同类型的文件上传,可以上传多个文件,并根据文件类型分别处理。

英文:

this is how i upload videos

router.post('/vid', upload.array('files', 5), async (req, res) => {
   try {
        const video = new Video();
        video.url = [];
        req.files.forEach((file) => {
          video.url.push(file.location);
        });
        const savedVideo = await video.save();
        res.json({
            message: 'Video uploaded successfully',
            video: savedVideo
        });
    } catch (error) {
       
    }
});

this how i upload pictures

router.post(`/products`, upload.array("photos", 10), async (req, res) => {
  try {
    let product = new Product();
    product.photos.push(...req.files.map(({
      location
    }) => location));
    await product.save();
  } catch (error) {
   
  }
});

this is my middleware

const aws = require("aws-sdk");
const multer = require("multer");
const multerS3 = require("multer-s3");

aws.config.update({
    secretAccessKey: process.env.AWSSecretKey,
    accessKeyId: process.env.AWSAccessKeyId,
    region: 'eu-north-1', // Update the region to 'eu-north-1'
    correctClockSkew: true
  });

const s3 = new aws.S3();

const upload = multer({
    storage: multerS3({
        s3: s3,
        bucket: 'ajibs',
        acl: 'public-read',
        metadata: (req, file, cb) => {
            cb(null, { fieldName: file.fieldname });
        },
        key: (req, file, cb) => {
            cb(null, Date.now().toString())
        }
    })
})

module.exports = upload;

both video and picture upload works fine if i use it in seperate route
please how can i upload both pictures and videos in one route

if i do this

upload.array(["photos","files"], 10)

i get this error

MulterError: Unexpected field

please how can i go about this

答案1

得分: 2

以下是翻译好的部分:

这是一个工作示例,您需要做的是将数组更改为字段,以获取照片和视频,不要忘记在模式中添加照片名称。

英文:

this a working example ,what you'll need to do is change array to fields to get both photos and video, dont forget to add the photos name in your schema

router.post('/media', upload.fields([{ name: 'videos', maxCount: 5 }, { name: 'photos', maxCount: 10 }]), async (req, res) => {
   try {
        const video = new Video();
        video.title = req.body.title;
        video.url = [];
        video.photos = [];

        // Process uploaded videos
        if (req.files['videos']) {
            req.files['videos'].forEach((file) => {
                video.url.push(file.location);
            });
        }

        // Process uploaded photos
        if (req.files['photos']) {
            req.files['photos'].forEach((file) => {
                video.photos.push(file.location);
            });
        }

        console.log(video);

        // Save the video to the database
        const savedVideo = await video.save();

        res.json({
            message: 'Media uploaded successfully',
            video: savedVideo
        });
    } catch (error) {
        console.error(error);
        res.status(500).json({
            error: 'An error occurred while uploading the media'
        });
    }
});

huangapple
  • 本文由 发表于 2023年7月3日 03:34:59
  • 转载请务必保留本文链接:https://go.coder-hub.com/76600499.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定