代码之家  ›  专栏  ›  技术社区  ›  Fishcount5698

使用multer作为中间件从两个字段上传两个文件

  •  0
  • Fishcount5698  · 技术社区  · 2 年前

    我试图用multer从两个字段上传两个文件扩展名不同的文件,但当我用postman尝试时,文件的结果总是空的,我的问题的解决方案是什么?这是我的密码

    中间件/上传Pub

    const multer = require('multer')
    
    exports.uploadEpub = (epubFile, coverFile) => {
    const storage = multer.diskStorage({
        destination: function (req, file, cb) {
            cb(null, "uploads")
        },
        filename: function (req, file, cb) {
            cb(null, Date.now() + '-' + file.originalname.replace(/\s/g, ""))
        }
    })
    
    const upload = multer({
        storage
    }).fields([{name: "bookFile", maxCount: 1},{name: "coverFile", maxCount: 1}])
    }
    

    管理员/书籍

    exports.addBook = async (req, res) => {
    try {
        const { ...data } = req.body
    
        const newBook = await book.create({
            ...data,
            bookFile: req.file,
            coverFile: req.file
        })
        let bookData = await book.findOne({
            where: {
                id: newBook.id
            },
            attributes:{
                exclude: ['createdAt','updatedAt']
            }
        })
    
        bookData = JSON.parse(JSON.stringify(bookData))
        res.send({
            status: "Success",
            Book: {
                ...bookData
            }
        })
    } catch (error) {
        console.log(error)
        res.status(500).send({
            status: "Failed",
            message: "Server Error"
        })
    }
    }
    
    1 回复  |  直到 2 年前
        1
  •  0
  •   jkalandarov    2 年前

    穆特设置

    const multer = require('multer')
    const path = require('path')
    const { nanoid } = require('nanoid')
    
    //Set Storage Engine
    const storage = multer.diskStorage({
        destination: './public/uploads/',
        filename: (req, file, callback) => {
            const id = nanoid(6)
            const newFilename = `${file.fieldname}_${id}-${new Date().toISOString().replace(/:/g, '-')}${path.extname(file.originalname)}`
            callback(null, newFilename)
        }
    })
    
    const upload = multer({
        storage: storage,
        limits: { fileSize: 5572864 }, // up to 5.5 MB
        fileFilter: (req, file, callback) => {
            checkFileType(file, callback)
        },
    })
    
    //Check File Type
    const checkFileType = (file, cb) => {
        //Allowed extensions
        const fileType = /jpeg|jpg|png|gif|svg|pdf|epub/
    
        //Check extension
        const extname = fileType.test(path.extname(file.originalname).toLowerCase())
    
        //Check mimetype
        const mimetype = fileType.test(file.mimetype)
    
        if (extname && mimetype) {
            return cb(null, true)
        } else {
            return cb('Error: wrong file type!')
        }
    }
    
    module.exports = upload
    

    /*****中间产品。js*****/

    module.exports.imageUploader = (req, res, next)=>{
        const files = req.files
        const uploadedFiles = []
        for (var i = 0; i <images.length; i++){
            uploadFiles.push('https://yourserver.com/public/uploads/' + files[i].filename)
        }
        req.uploadFiles = uploadFiles.toString() //appending files to req
        next()
        return
    }
    

    /****索引。js或应用程序。js****///定义路线的位置

    router.post('/books/add', upload.array('images', 10), imageUploader, book.addBook) // allowing up to 10 files to be uploaded, calling imageUploader as a middleware
    

    /***控制器/书本***/

    exports.addBook = async (req, res) => {
       const uploadedFiles = req.uploadFiles; //catching files from imageUploader middleware
    
       // ... rest of your code
    }
    
        2
  •  0
  •   Ethan    2 年前

    尝试将文件作为表单数据上传到postman中,并将密钥与您在multer中设置的名称相同,postman将如下所示:

    enter image description here