创建fileshare模型,将上传文件的数据写入数据库

This commit is contained in:
赵鑫 2022-08-26 16:33:49 +08:00
parent d26791a77f
commit c34c1a2d38
2 changed files with 21 additions and 5 deletions

12
models/fileshare.js Normal file
View File

@ -0,0 +1,12 @@
const mongoose = require('mongoose')
const FileshareSchema = new mongoose.Schema({
md5: { type: String, require: true },
size: { type: Number, require: true },
encoding: { type: String, require: true },
mimetype: { type: String, require: true },
filename: { type: String, require: true },
password: { type: String, require: true },
downloads: { type: Number, default: 0 },
timestamp: { type: Date, default: Date.now },
})
module.exports = mongoose.model('Fileshare', FileshareSchema)

View File

@ -6,6 +6,7 @@ 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)
@ -26,8 +27,11 @@ 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 = {
id: req.file.filename,
md5,
size: req.file.size,
encoding: req.file.encoding,
@ -35,10 +39,10 @@ app.post('/upload', upload.single('file'), async (req, res) => {
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) // 删除临时文件
// 写入数据库
const fileshare = new Fileshare(file)
file.id = (await fileshare.save()).id
console.table(file)
res.status(201).render('index', { file })
})
const server = app.listen(SERVER_PORT, SERVER_HOST, () => {