gpt4 book ai didi

javascript - 如何在调用post方法后更改使用multer上传的文件的名称

转载 作者:行者123 更新时间:2023-12-03 03:12:45 24 4
gpt4 key购买 nike

我想使用 multer 保存具有唯一名称的图片。文件名的模式为 file.orginalName + req.body.userName

我的代码:

const express = require('express');
const router = express.Router();
const multer = require('multer');
const bcrypt = require('bcrypt');
const passport = require('passport');

let User = require('../models/user');

const storage = multer.diskStorage({
destination: function (req, file, cb) {
cb(null, 'uploads/avatars/')
},
filename: function (req, file, cb) {
cb(null, file.originalname)
}
});

const upload = multer({ storage: storage })


router.post('/register', upload.single('avatar'), (req, res) => {

////here I want to change the uploaded avatar name then save to DB
});

module.exports = router;

如何更改代码以重命名 post 方法中的图片名称?

最佳答案

const storage = multer.diskStorage({
destination: function (req, file, cb) {
cb(null, 'uploads/avatars/')
},
filename: function (req, file, cb) {
//console.log(req.body)
cb(null, file.originalname)
}
});

const upload = multer({ storage: storage })

router.post('/register', (req, res) => {
upload(req, res, function(err) {
if(err) {
//stuff when error while file uploading
} else {
//file uploaded
}
})
});

关于javascript - 如何在调用post方法后更改使用multer上传的文件的名称,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46896117/

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