gpt4 book ai didi

node.js - 如果不存在,multer 创建文件夹

转载 作者:行者123 更新时间:2023-12-04 14:29:47 30 4
gpt4 key购买 nike

我在 multer 的文档中看到,如果文件夹不存在,multer 将不会创建文件夹。如果文件夹不存在,如何创建?

import multer from 'multer'
import crypto from 'crypto'
import { extname, resolve } from 'path'
import slug from 'slug'

export default {
storage: multer.diskStorage({
destination: resolve(__dirname, '..', '..', 'uploads', 'gallery'),
filename: (req, file, cb) => {
const { id, description } = req.body

crypto.randomBytes(8, (err, res) => {
if (err) return cb(err)

return cb(null, id + '/' + res.toString('hex') + '/' + slug(description, { lower: true }) + extname(file.originalname))
// return cb(null, res.toString('hex') + extname(file.originalname))
})
}
})
}

最佳答案

我有改变:

import multer from 'multer'
import crypto from 'crypto'
import { extname } from 'path'
import slug from 'slug'
import fs from 'fs'

export default {
storage: multer.diskStorage({
destination: (req, file, cb) => {
const { id } = req.body
const path = `./uploads/gallery/${id}`
fs.mkdirSync(path, { recursive: true })
return cb(null, path)
},
filename: (req, file, cb) => {
const { description } = req.body

crypto.randomBytes(3, (err, res) => {
if (err) return cb(err)

return cb(null, slug(description, { lower: true }) + '_' + res.toString('hex') + extname(file.originalname))
})
}
})
}

关于node.js - 如果不存在,multer 创建文件夹,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59646445/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com