重写POST upload/路由基本实现单文件上传并重命名的功能
This commit is contained in:
parent
67cd03f053
commit
d26791a77f
33
server.js
33
server.js
@ -1,4 +1,9 @@
|
|||||||
const { SERVER_HOST, SERVER_PORT, MONGODB_URL } = require('./config')
|
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 express = require('express')
|
||||||
const mongoose = require('mongoose')
|
const mongoose = require('mongoose')
|
||||||
mongoose.connect(MONGODB_URL, (error) => {
|
mongoose.connect(MONGODB_URL, (error) => {
|
||||||
@ -16,14 +21,26 @@ app.use(express.json())
|
|||||||
app.get('/', (req, res) => {
|
app.get('/', (req, res) => {
|
||||||
res.render('index')
|
res.render('index')
|
||||||
})
|
})
|
||||||
app.post('/upload', (req, res) => {
|
const upload = multer({ dest: TEMP_PATH, limits: { fileSize: UPLOAD_SIZE_LIMIT } })
|
||||||
res.sendStatus(201)
|
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)
|
||||||
|
const file = {
|
||||||
|
id: req.file.filename,
|
||||||
|
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) : '',
|
||||||
|
}
|
||||||
|
if (!fs.existsSync(file_save_path)) {
|
||||||
|
fs.cpSync(file_temp_path, file_save_path) // 复制文件到UPLOAD_PATH
|
||||||
|
}
|
||||||
|
fs.unlinkSync(file_temp_path) // 删除临时文件
|
||||||
|
res.status(201).render('index', { file })
|
||||||
})
|
})
|
||||||
const server = app.listen(SERVER_PORT, SERVER_HOST, () => {
|
const server = app.listen(SERVER_PORT, SERVER_HOST, () => {
|
||||||
console.info(`server is running at http://${SERVER_HOST}:${SERVER_PORT}`)
|
console.info(`server is running at http://${SERVER_HOST}:${SERVER_PORT}`)
|
||||||
})
|
})
|
||||||
/**
|
|
||||||
* "bcrypt": "^5.0.1",
|
|
||||||
"md5-file": "^5.0.0",
|
|
||||||
"multer": "^1.4.5-lts.1",
|
|
||||||
*/
|
|
||||||
|
Loading…
Reference in New Issue
Block a user