实现了文件下载时界面及密码的输入

This commit is contained in:
赵鑫 2022-08-26 20:29:00 +08:00
parent 4006decb81
commit 503fae7cc7

View File

@ -20,7 +20,7 @@ app.use(express.static('public'))
app.use(express.urlencoded({ extended: true }))
app.use(express.json())
app.get('/', (req, res) => {
res.render('index')
res.render('upload')
})
const upload = multer({ dest: TEMP_PATH, limits: { fileSize: UPLOAD_SIZE_LIMIT } })
app.post('/upload', upload.single('file'), async (req, res) => {
@ -31,27 +31,35 @@ app.post('/upload', upload.single('file'), async (req, res) => {
fs.cpSync(file_temp_path, file_save_path) // 复制文件到UPLOAD_PATH
}
fs.unlinkSync(file_temp_path) // 删除临时文件
const file = {
let file = {
md5,
size: req.file.size,
encoding: req.file.encoding,
mimetype: req.file.mimetype,
filename: req.file.originalname,
// 解决了multer将中文文件名错误编码的问题
filename: Buffer.from(req.file.originalname, 'latin1').toString('utf8'),
password: req.body.password ? await bcrypt.hash(req.body.password, 16) : '',
}
// 写入数据库
console.log(req.file)
console.log(file)
const fileshare = new Fileshare(file)
file.id = (await fileshare.save()).id
console.table(file)
res.status(201).render('index', { file })
file = await fileshare.save()
console.log(file)
res.status(201).render('upload', { file })
})
app.get('/file/:id', async (req, res) => {
const file = await Fileshare.findByIdAndUpdate(req.params.id, { $inc: { downloads: 1 } })
const file = await Fileshare.findById(req.params.id)
res.render('download', { file })
})
app.post('/file/:id', async (req, res) => {
const file = await Fileshare.findById(req.params.id)
if (file) {
const file_path = path.join(SAVE_PATH, file.md5)
if (file.password == '') {
res.status(200).download(file_path, file.filename)
if (file.password == '' || (await bcrypt.compare(req.body.password, file.password)) == true) {
await file.update({ $inc: { downloads: 1 } })
res.status(200).download(path.join(SAVE_PATH, file.md5), file.filename)
} else {
res.sendStatus(401)
}
} else {
res.sendStatus(404)