63 lines
2.2 KiB
JavaScript
63 lines
2.2 KiB
JavaScript
const { SERVER_HOST, SERVER_PORT, MONGODB_URL, TEMP_PATH, SAVE_PATH, UPLOAD_SIZE_LIMIT } = require('./config')
|
|
const fs = require('fs')
|
|
const path = require('path')
|
|
const multer = require('multer')
|
|
const bcrypt = require('bcrypt')
|
|
const md5file = require('md5-file')
|
|
const express = require('express')
|
|
const mongoose = require('mongoose')
|
|
const Fileshare = require('./models/fileshare')
|
|
mongoose.connect(MONGODB_URL, (error) => {
|
|
if (error) {
|
|
console.error(error)
|
|
} else {
|
|
console.info('mongodb connected successfully')
|
|
}
|
|
})
|
|
const app = express()
|
|
app.set('view engine', 'pug')
|
|
app.use(express.static('public'))
|
|
app.use(express.urlencoded({ extended: true }))
|
|
app.use(express.json())
|
|
app.get('/', (req, res) => {
|
|
res.render('index')
|
|
})
|
|
const upload = multer({ dest: TEMP_PATH, limits: { fileSize: UPLOAD_SIZE_LIMIT } })
|
|
app.post('/upload', upload.single('file'), async (req, res) => {
|
|
const file_temp_path = path.join(TEMP_PATH, req.file.filename)
|
|
const md5 = await md5file(file_temp_path)
|
|
const file_save_path = path.join(__dirname, SAVE_PATH, md5)
|
|
if (!fs.existsSync(file_save_path)) {
|
|
fs.cpSync(file_temp_path, file_save_path) // 复制文件到UPLOAD_PATH
|
|
}
|
|
fs.unlinkSync(file_temp_path) // 删除临时文件
|
|
const file = {
|
|
md5,
|
|
size: req.file.size,
|
|
encoding: req.file.encoding,
|
|
mimetype: req.file.mimetype,
|
|
filename: req.file.originalname,
|
|
password: req.body.password ? await bcrypt.hash(req.body.password, 16) : '',
|
|
}
|
|
// 写入数据库
|
|
const fileshare = new Fileshare(file)
|
|
file.id = (await fileshare.save()).id
|
|
console.table(file)
|
|
res.status(201).render('index', { file })
|
|
})
|
|
app.get('/file/:id', async (req, res) => {
|
|
const file = await Fileshare.findByIdAndUpdate(req.params.id, { $inc: { downloads: 1 } })
|
|
if (file) {
|
|
const file_path = path.join(SAVE_PATH, file.md5)
|
|
if (file.password == '') {
|
|
res.status(200).download(file_path, file.filename)
|
|
} else {
|
|
}
|
|
} else {
|
|
res.sendStatus(404)
|
|
}
|
|
})
|
|
const server = app.listen(SERVER_PORT, SERVER_HOST, () => {
|
|
console.info(`server is running at http://${SERVER_HOST}:${SERVER_PORT}`)
|
|
})
|