后台管理系统中上传图片的实现
使用工具:前端vite+vue3+element-plus
思路:前端上传调用后台nodejs编写的接口,nodejs使用multer中间件将前端传过来的文件或图片重命名并保存到指定文件夹下,再返回一个线上地址给前端用来访问该文件或图片
前端代码:
使用element-plus实现上传功能
注意:该部分代码使用的是ts语法,如果使用的是vue2,可至文章底部连接查看对应代码
<el-upload
class="upload-demo"
action="http://localhost:3000/api/files/upload"
:on-preview="handlePreview"
:on-remove="handleRemove"
:before-remove="beforeRemove"
multiple
:limit="3"
:on-success="handleAvatarSuccess"
:on-exceed="handleExceed"
:file-list="fileList"
>
<el-button size="small" type="primary">点击上传</el-button>
</el-upload>
<script lang="ts" setup>
import { ref } from 'vue'
import { ElMessageBox,ElMessage,MessageParamsWithType } from 'element-plus'
const fileList = ref([]);
const handleAvatarSuccess = (res: { code: number; message: MessageParamsWithType; }, file: { response: { filename: any; }; }) => {
if (res.code === 10000) {
ElMessage.error(res.message);
fileList.value.splice(fileList.value.length, 1);
} else {
ElMessage.success('上传成功');
//返回新的图片名,可使用服务器地址访问该图片
console.log(file.response.filename);
}
}
const handleRemove = (file: any, currentFileList: any) => {
console.log(file, currentFileList);
}
主要是后端实现过程,前端不做解释
文件目录如上图
需要下载multer和mime,直接npm i multer mime --save-dev 就可以了
Upload.js文件内容如下
const path = require('path')
const multer = require('multer')
const mime = require('mime')
// 定义文件存储路径和文件名
const storage = multer.diskStorage({
destination: function (req, file, cb) {
cb(null, path.join(__dirname, '../public/uploads'))
},
filename: function (req, file, cb) {
console.log('file', file);
const ext = mime.getExtension(file.mimetype);
const filename = `${file.fieldname}-${Date.now()}.${ext}`
cb(null, filename)
}
})
// 限制上传文件一些数据大小
const limits = {
fileSize: 200 * 1000, // 200kb
files: 1,
}
// 过滤器
const fileFilter = (req, file, cb) => {
// 这个函数应该调用 `cb` 用boolean值来
// 指示是否应接受该文件
// 接受的文件类型
const accessTypes = ['image/png', 'image/jpg', 'image/jpeg', 'image/gif']
if (!accessTypes.includes(file.mimetype)) {
cb(new Error('文件类型必须是 .png、.jpg、.gif'))
} else {
// 接受这个文件,使用`true`
cb(null, true)
}
}
const upload = multer({
storage,
limits,
fileFilter
}).single('file')
const uploadMiddleware = (req, res, next) => {
upload(req, res, (err) => {
res.set('Content-Type', 'application/json; charset=utf-8')
if (err instanceof multer.MulterError) {
// 发生 MulterError 错误
console.log('MulterError', err.message);
if (err.message.includes('File too large')) {
res.send({
code: 10000,
message: `文件太大,超过${limits.fileSize / 1000} kb啦`
})
} else {
res.send({
code: 10000,
message: err.message
})
}
} else if (err) {
// 发生 js Error 错误
res.send({
code: 10000,
message: err.message
})
}
// 一切都好
next()
})
}
module.exports = uploadMiddleware
在index.js中
引入upload.js中的uploadMiddleware
const uploadMiddleware = require('./middlewares/upload.js')
//实现图片上传并返回图片的新名字给前端
const uploadControl = (req, res, next) => {
console.log('req.file', req.file);
res.send(req.file)
}
//创建接口
app.use('/api/files/upload', uploadMiddleware, uploadControl)
最后,将保存好的图片暴露出去,使前端可以使用在线路径访问该图片
app.use(express.static('./public/uploads'));
实例:
建议再index中添加header头来解决跨域,否则项目在调用该接口时会因为端口不同而跨域
index.js完整代码如下
const express = require('express')
const bodyParser=require("body-parser")
const mysql = require('mysql')
const app = express()
const port = 3000
const uploadMiddleware = require('./middlewares/upload.js')
app.use(bodyParser.urlencoded({extended: false}))
app.use(bodyParser.json())
//跨域配置
app.all('*', function (req, res, next) {
res.header('Access-Control-Allow-Origin', '*');
res.header('Access-Control-Allow-Headers', 'Content-Type, Content-Length, Authorization, Accept, X-Requested-With , yourHeaderFeild');
res.header('Access-Control-Allow-Methods', 'PUT, POST, GET, DELETE, OPTIONS');
next();
});
// 连接数据库
const connection = mysql.createConnection({
host: 'localhost',
port: 3306,
user: ' mysql用户名', //
password: '密码', // 密码
database: '数据库名' // 数据库名
})
connection.connect()
//图片上传功能
//req.file就是上传的文件信息
const uploadControl = (req, res, next) => {
console.log('req.file', req.file);
res.send(req.file)
}
app.use('/api/files/upload', uploadMiddleware, uploadControl)
app.use(express.static('./public/uploads'));
app.listen(port, () => {
console.log(`Example app listening on port ${port}`)
})
Req.file中内容
参考文档:Node.js 高级篇(六):手把手教你使用和理解 Multer 实现文件上传,包懂 O(∩_∩)O~_nodejs multer 大文件___畫戟__的博客-CSDN博客