我正在尝试使用express上传图像或pdf(通常是文件),遇到的两个模块是multer和busboy。图像上传过程很容易,但是我遇到了两个问题。我想要的是上传带有名称的图像,以后也可以将其插入数据库中,以便当我想要检索文件时,我可以简单地将文件名放在img标签中并完成操作。由于某些原因,在Busboy中req.body为空,因此我无法再使用诸如该人的用户名之类的形式传递信息。在multer中,我们无法自定义名称,而必须在multer的初始设置中指定文件名。我想要的是一种表格,使我们能够输入用户名和文件。然后,我可以使用该用户名生成一个随机字符串,该字符串对于文件和我将要输入数据库的条目都是相同的,以便以后可以轻松地进行获取。下面给出了busboy和multer的设置和用法:
busboy设置:
router.post('/profileUpload', function(req,res){
let username = 'dual'
let busboy = new Busboy({ headers: req.headers });
busboy.on('file', function(fieldname, file, filename, encoding, mimetype) {
let saveTo = './public/profileimage/'+`${username}.jpg`;
console.log('Uploading: ' + saveTo);
file.pipe(fs.createWriteStream(saveTo));
});
busboy.on('finish', function() {
console.log('Upload complete');
});
return req.pipe(busboy);
})
马尔特设置:
const multer = require('multer');
var storage = multer.diskStorage({
destination: './public/reports',
filename: function (req, file, cb){
cb(null,'report' + Date.now() + path.extname(file.originalname))
}
})
var upload = multer({ storage: storage })
router.post('/reportUpload',upload.single('doc'),function(req,res){
let usernameLab = req.session.usernameLab
let username = req.body.patientUsername
var d = new Date()
var uniqstring = Date.now()
let uniqname = 'report' + uniqstring
var date = `${d.getFullYear()}/${d.getMonth()+1}/${d.getDate()}`
let testName = req.body.testName
let department = req.body.department
let params = [username, usernameLab, uniqname, date, testName, department]
let promise = queries.reportUpload(params)
promise.then(function(){
res.redirect('/reportUpload?upload=success')
})
});