实现文件预览功能

This commit is contained in:
赵鑫 2022-08-27 00:46:04 +08:00
parent ab862d08fd
commit 659aa9d111
5 changed files with 33 additions and 4 deletions

View File

@ -32,3 +32,12 @@ form button {
color: gray;
font-size: small;
}
audio {
width: 360px;
}
img {
width: 360px;
object-fit: cover;
}

View File

@ -49,7 +49,18 @@ app.post('/upload', upload.single('file'), async (req, res) => {
})
res.status(201).render('upload', { file })
})
app.get('/file/:id', async (req, res) => {
app.get('/file/:md5', async (req, res) => {
try {
const file = await Filesharing.findOne({ md5: req.params.md5 })
if (!file) throw '试图下载不存在的文件'
if (file.password != '') throw '访问的文件需要密码'
res.sendFile(path.join(__dirname, UPLOAD_SAVE_PATH, req.params.md5))
} catch (error) {
console.error(error)
res.sendStatus(404)
}
})
app.get('/download/:id', async (req, res) => {
try {
if (!req.params.id.match(/^[0-9a-fA-F]{24}$/)) throw '格式错误的ObjectId'
const file = await Filesharing.findById(req.params.id)
@ -60,7 +71,7 @@ app.get('/file/:id', async (req, res) => {
res.sendStatus(404)
}
})
app.post('/file/:id', async (req, res) => {
app.post('/download/:id', async (req, res) => {
try {
if (!req.params.id.match(/^[0-9a-fA-F]{24}$/)) throw '格式错误的ObjectId'
const file = await Filesharing.findById(req.params.id)

View File

@ -28,3 +28,12 @@ html(lang='zh')
label(for='password_input') 密码
input(id='password_input' name='password' type='password' autocomplete='off' required)
button(id='download_button' type='submit') 下载
if !file.password
- var mimetype = file.mimetype.split('/')[0]
- var src = '/file/' + file.md5
if mimetype == 'image'
p 预览
img(src=src)
if mimetype == 'audio'
p 预览
audio(controls src=src)

View File

@ -17,7 +17,7 @@ html(lang='zh')
else
for file in filesharing
li
a(href=`/file/${file.id}`)= file.filename
a(href=`/download/${file.id}`)= file.filename
if file.password
span   ㊙️
span.small   ( #{moment(file.createdAt).fromNow()}, #{file.downloads} 次下载 )

View File

@ -18,7 +18,7 @@ html(lang='zh')
var #{file.filename}  
| 分享成功!
p 链接  
- const url = '/file/' + file.id
- const url = '/download/' + file.id
a(href=url)= url
form(method='POST' action='/upload' enctype='multipart/form-data')
label(for='file_input') 文件