使用multerS3和NodeJs上传多个文件

如何解决使用multerS3和NodeJs上传多个文件

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

:: UPDATE :: 文件正在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,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)
      }
    })

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其他元素将获得点击?
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。)
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbcDriver发生异常。为什么?
这是用Java进行XML解析的最佳库。
Java的PriorityQueue的内置迭代器不会以任何特定顺序遍历数据结构。为什么?
如何在Java中聆听按键时移动图像。
Java“Program to an interface”。这是什么意思?
Java在半透明框架/面板/组件上重新绘画。
Java“ Class.forName()”和“ Class.forName()。newInstance()”之间有什么区别?
在此环境中不提供编译器。也许是在JRE而不是JDK上运行?
Java用相同的方法在一个类中实现两个接口。哪种接口方法被覆盖?
Java 什么是Runtime.getRuntime()。totalMemory()和freeMemory()?
java.library.path中的java.lang.UnsatisfiedLinkError否*****。dll
JavaFX“位置是必需的。” 即使在同一包装中
Java 导入两个具有相同名称的类。怎么处理?
Java 是否应该在HttpServletResponse.getOutputStream()/。getWriter()上调用.close()?
Java RegEx元字符(。)和普通点?