mysql 以multer为中间件上传两个字段的两个文件

bzzcjhmw  于 2023-02-21  发布在  Mysql
关注(0)|答案(3)|浏览(130)

我试图上传两个文件与不同的文件扩展名与multer从两个字段,但当我尝试与 Postman 的结果总是为文件是空,什么是我的问题的解决方案?这里是我的代码
中间件/上传Epub

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"
    })
}
}
dgiusagp

dgiusagp1#

Multer设置

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
}

/index.js或app.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
}
ruarlubt

ruarlubt2#

尝试在postman中将文件作为form-data上传,并将与您在multer中设置的名称相同的密钥放入,postman将如下所示:

fjnneemd

fjnneemd3#

"试试这个"
const cpUpload =上载.字段([{名称:“化身”,最大计数:1 },{姓名:'库',最大计数:8 }])
app.post('/酷配置文件',cpUpload,函数(请求,资源,下一个){ })

相关问题