使用 multerS3 和 NodeJs 上传多个文件

upload multiple files using multerS3 and NodeJs

我已经尝试了好几天,但似乎无法弄清楚哪里出了问题。我的代码适用于在本地文件夹中上传单个文件,但即使我分别在 multer 和控制器函数中使用 upload.array()req.files,似乎也无法上传多个文件。而当我尝试在我的 s3 存储桶中上传 single/multiple 文件时,根本没有上传任何内容。下面我也会提供我的模型结构,以备不时之需。

::更新:: 文件正在上传到 s3 存储桶中,但数据库无法捕获文件路径。 imagePath 数据库内部变为空白

route.js:

const ProductController = require('./../controllers/productController');
const appConfig = require("./../config/appConfig");
const multer = require('multer');
const aws = require('aws-sdk');
const multerS3 = require('multer-s3');
const path = require('path');
const s3 = new aws.S3({ accessKeyId: "***", secretAccessKey: "***" });
 var upload = multer({
    storage: multerS3({
      s3: s3,
      bucket: 'mean-ecom',
      metadata: function (req, file, cb) {
        cb(null, {fieldName: file.originalname + path.extname(file.fieldname)});
      },
      key: function (req, file, cb) {
        cb(null, Date.now().toString())}})});
let setRouter = (app) => {
    let baseUrl = appConfig.apiVersion;
app.post(baseUrl+'/post-product', upload.single('imagePath'), ProductController.postProduct)}
   module.exports = {
     setRouter: setRouter}

ProductController.postProduct:

const ProductModel = mongoose.model('Product')

let postProduct = (req, res) => {
    let newProduct = new ProductModel({

                imagePath: req.file && req.file.path})
            newProduct.save((err, result) => {
                if (err) { console.log('Error at saving new Product :: ProductController', err);
                 res.send(err);
            } else { 
                console.log('Successfully saved new Product'); res.send(result) }
            })}

productModel.js

const mongoose = require('mongoose');
const Schema = mongoose.Schema;
let productSchema = new Schema(
    {
       imagePath: {
                type: String,
                default: ''    }})
mongoose.model('Product', productSchema);

您需要做的第一件事是将模型的 imagePath 属性 从字符串更改为字符串数组,这样您就可以存储多个图像

const Schema = mongoose.Schema;
let productSchema = new Schema(
    {
       imagePath: {type: Array}
    })
mongoose.model('Product', productSchema)

然后,在路由器中,你应该使用upload.any()upload.array()应该以同样的方式工作)。 最后,如果你想将文件位置存储在模型数组中,你循环抛出更新模型的文件。

let postProduct = (req, res) => {
    // We create a temporal array with the files locations
    let files = [];
    
    // We loop throw the req.files array and store their locations in the temporal files array
    for (let i = 0; i < req.files.length; i++) {
      let file = req.files[i].location
      files.push(file)
    }

    let newProduct = new ProductModel({
            imagePath: files}) //We create the model with the temp array

    newProduct.save((err, result) => {
      if (err) {
        console.log('Error at saving new Product :: ProductController', err);
        res.send(err);
      }
      else{
        console.log('Successfully saved new Product');
        res.send(result)
      }
    })