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

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.urlencoded({ extended: true }))
app.use(express.json()) app.use(express.json())
app.get('/', (req, res) => { app.get('/', (req, res) => {
res.render('index') res.render('upload')
}) })
const upload = multer({ dest: TEMP_PATH, limits: { fileSize: UPLOAD_SIZE_LIMIT } }) const upload = multer({ dest: TEMP_PATH, limits: { fileSize: UPLOAD_SIZE_LIMIT } })
app.post('/upload', upload.single('file'), async (req, res) => { 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.cpSync(file_temp_path, file_save_path) // 复制文件到UPLOAD_PATH
} }
fs.unlinkSync(file_temp_path) // 删除临时文件 fs.unlinkSync(file_temp_path) // 删除临时文件
const file = { let file = {
md5, md5,
size: req.file.size, size: req.file.size,
encoding: req.file.encoding, encoding: req.file.encoding,
mimetype: req.file.mimetype, 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) : '', password: req.body.password ? await bcrypt.hash(req.body.password, 16) : '',
} }
// 写入数据库 // 写入数据库
console.log(req.file)
console.log(file)
const fileshare = new Fileshare(file) const fileshare = new Fileshare(file)
file.id = (await fileshare.save()).id file = await fileshare.save()
console.table(file) console.log(file)
res.status(201).render('index', { file }) res.status(201).render('upload', { file })
}) })
app.get('/file/:id', async (req, res) => { 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) { if (file) {
const file_path = path.join(SAVE_PATH, file.md5) if (file.password == '' || (await bcrypt.compare(req.body.password, file.password)) == true) {
if (file.password == '') { await file.update({ $inc: { downloads: 1 } })
res.status(200).download(file_path, file.filename) res.status(200).download(path.join(SAVE_PATH, file.md5), file.filename)
} else { } else {
res.sendStatus(401)
} }
} else { } else {
res.sendStatus(404) res.sendStatus(404)