【VUE案例练习】前端vue2+element-ui,后端nodo+express实现‘‘文件上传/删除‘‘功能

ops/2025/2/4 8:05:56/

近期在做跟毕业设计相关的数据后台管理系统,其中的列表项展示有图片展示,添加/编辑功能有文件上传。

“文件上传/删除”也是我们平时开发会遇到的一个功能,这里分享个人的实现过程,与大家交流谈论~

一、准备工作

  • 本次案例使用的node版本是18.16.1
  • 前端vue2+element-ui
  • 后端使用node+express
  • 安装对应库:element-ui、axios、multer

注意:本篇重点介绍文件上传的相关功能,后端express的具体使用可以看我的express专栏~

express专栏

二、前端

文件上传组件,来自element-ui组件库

注意:自行安装组件库

Element - The world's most popular Vue UI framework

关于组件,有些展示和功能需要对应设置(比如文件上传的服务器地址,删除后端文件等等)才可以正常使用,所以我对代码进行了修改补充。

组件代码

<template><div><el-uploadref="upload"action="http://localhost:4000/api/upload"  //文件上传的接口list-type="picture-card":on-preview="handlePictureCardPreview":on-remove="handleRemove":file-list="fileList":on-change="handleFileChange":on-success="handleUploadSuccess":on-error="handleUploadError"name="file"><i class="el-icon-plus" /></el-upload><el-dialog :visible.sync="dialogVisible"><img width="100%" :src="dialogImageUrl" alt=""></el-dialog></div>
</template>

 变量和相关函数

注意:需要安装axios(若安装则跳过)

javascript">npm install axios
javascript"><script>
import Axios from 'axios'
export default {data() {return {dialogImageUrl: '', //预览时展示的图片dialogVisible: false,fileList: [] // 用于存储文件列表}},methods: {// 生成文件预览 URLhandleFileChange(file, fileList) {file.url = URL.createObjectURL(file.raw)this.fileList = fileList},// 删除文件handleRemove(file, fileList) {this.fileList = fileList// 调用后端删除接口if (file.response && file.response.data) {this.deleteFile(file.response.data)} else {this.$message.warning('文件尚未上传成功,无法删除')}},// 预览图片handlePictureCardPreview(file) {this.dialogImageUrl = file.urlthis.dialogVisible = true},// 文件上传成功handleUploadSuccess(response, file) {console.log('文件上传成功', response)if (response.code === 0) {// 从后端响应中获取图片的 URLconst imageUrl = response.data// 更新 fileList 中的文件 URLconst index = this.fileList.findIndex(f => f.uid === file.uid)if (index !== -1) {this.fileList[index].url = imageUrlthis.fileList[index].response = response // 保存后端返回的响应}this.$message.success('文件上传成功')} else {this.$message.error('文件上传失败: ' + response.msg)}},// 文件上传失败handleUploadError(err, file) {console.error('文件上传失败', err)this.$message.error('文件上传失败')},deleteFile(filename) {// 去掉前缀 /public/static/upload/const pureFilename = filename.replace('/public/static/upload/', '')// 调用后端删除接口Axios.delete(`http://localhost:4000/api/upload/${pureFilename}`).then(response => {if (response.data.code === 0) {this.$message.success('文件删除成功')} else {this.$message.error('文件删除失败: ' + response.data.msg)}}).catch(err => {console.error('文件删除失败', err)this.$message.error('文件删除失败')})}}
}
</script>

完整代码

 注意看:''localhost:4000''相关字眼(关于后端接口的,下文会作介绍)

javascript"><template><div><el-uploadref="upload"action="http://localhost:4000/api/upload"list-type="picture-card":on-preview="handlePictureCardPreview":on-remove="handleRemove":file-list="fileList":on-change="handleFileChange":on-success="handleUploadSuccess":on-error="handleUploadError"name="file"><i class="el-icon-plus" /></el-upload><el-dialog :visible.sync="dialogVisible"><img width="100%" :src="dialogImageUrl" alt=""></el-dialog></div>
</template><script>
import Axios from 'axios'
export default {data() {return {dialogImageUrl: '',dialogVisible: false,fileList: [] // 用于存储文件列表}},methods: {// 生成文件预览 URLhandleFileChange(file, fileList) {file.url = URL.createObjectURL(file.raw)this.fileList = fileList},// 删除文件handleRemove(file, fileList) {this.fileList = fileList// 调用后端删除接口if (file.response && file.response.data) {this.deleteFile(file.response.data)} else {this.$message.warning('文件尚未上传成功,无法删除')}},// 预览图片handlePictureCardPreview(file) {this.dialogImageUrl = file.urlthis.dialogVisible = true},// 文件上传成功handleUploadSuccess(response, file) {console.log('文件上传成功', response)if (response.code === 0) {// 从后端响应中获取图片的 URLconst imageUrl = response.data// 更新 fileList 中的文件 URLconst index = this.fileList.findIndex(f => f.uid === file.uid)if (index !== -1) {this.fileList[index].url = imageUrlthis.fileList[index].response = response // 保存后端返回的响应}this.$message.success('文件上传成功')} else {this.$message.error('文件上传失败: ' + response.msg)}},// 文件上传失败handleUploadError(err, file) {console.error('文件上传失败', err)this.$message.error('文件上传失败')},// 删除后端文件,参数传递的是文件名(经前端上传过后,返回给前端的文件名)deleteFile(filename) {// 去掉前缀 /public/static/upload/const pureFilename = filename.replace('/public/static/upload/', '')// 调用后端删除接口Axios.delete(`http://localhost:4000/api/upload/${pureFilename}`).then(response => {if (response.data.code === 0) {this.$message.success('文件删除成功')} else {this.$message.error('文件删除失败: ' + response.data.msg)}}).catch(err => {console.error('文件删除失败', err)this.$message.error('文件删除失败')})}}
}
</script><style>
.el-upload-list__item-thumbnail {width: 100%;height: 100%;object-fit: cover;
}
</style>

三、后端

1、搭建express应用

【express-generator】01-安装和基本使用

如果按照文章步骤(默认端口是3000,我这里设置成4000端口),则对应更换端口为4000,在创建的express项目的bin/www中进行修改。

2、新建文件夹以及文件

2.1、新建public/static/upload

这是存储上传文件的位置。

 2.2、新建routes/upload.js,用于撰写路由方法

安装multer,这是处理文件上传的相关库。

npm install multer

javascript">var express = require("express");
const multer = require("multer");
const { uploading } = require("../utils/tool");
const fs = require('fs');
const path = require('path');
var router = express.Router();// 文件上传接口
router.post("/", async function (req, res, next) {// single 方法里面书写上传控件的 name 值uploading.single("file")(req, res, function (err) {if (err instanceof multer.MulterError) {next("上传文件失败,请检查文件的大小,控制在 6MB 以内");} else {console.log("req.file>>>", req.file);const filePath = "/public/static/upload/" + req.file.filename;res.send({ code: 0, msg: "文件上传成功", data: filePath });}})
});// 文件删除接口
router.delete("/:filename", function (req, res, next) {const filename = req.params.filename;const filePath = path.join(__dirname, '../public/static/upload',filename);console.log("后端接收到的文件参数>>>",filename,"完整基本路径是>>>>",filePath);fs.unlink(filePath, (err) => {if (err) {console.error("删除文件失败", err);return res.status(500).send({ code: 1, msg: "删除文件失败" });}res.send({ code: 0, msg: "文件删除成功" });});
});module.exports = router;

2.3、新增utlis/tool.js,撰写工具类函数

javascript">const multer = require("multer");
const path = require("path");// 设置上传文件的引擎
const storage = multer.diskStorage({// 文件存储的位置destination: function (req, file, cb) {cb(null, __dirname + '/../public/static/upload');},// 上传到服务器的文件,文件名要做单独处理filename: function (req, file, cb) {// 获取文件名const basename = path.basename(file.originalname, path.extname(file.originalname));// 获取后缀名const extname = path.extname(file.originalname);// 构建新的名字const newName = basename + new Date().getTime() + Math.floor(Math.random() * 9000 + 1000) + extname;cb(null, newName);}
})module.exports.uploading = multer({storage: storage,limits: {fileSize: 6000000,files: 1}
})

 3、在app.js中引入和使用

javascript">var createError = require('http-errors');
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');
const cors = require('cors');
// 文件上传
const multer = require('multer');
const fs = require('fs');
// const path = require('path');var indexRouter = require('./routes/index');
var usersRouter = require('./routes/users');
var uploadRouter = require('./routes/upload');
var app = express();// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');// 允许所有来源访问
app.use(cors());// 文件上传
// const upload = multer({ dest: 'static/upload/' });
app.use(express.static(path.join(__dirname, 'public')));
app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use('/', indexRouter);
app.use('/users', usersRouter);
app.use('/api/upload/', uploadRouter);// error handler
app.use(function(err, req, res, next) {// set locals, only providing error in developmentres.locals.message = err.message;res.locals.error = req.app.get('env') === 'development' ? err : {};// render the error pageres.status(err.status || 500);res.render('error');
});module.exports = app;

四、测试

1、上传文件(图片)

 查看存储上传文件的位置

 2、删除文件(图片)

前端组件,鼠标进入到图片区域,点击删除按键

前端作出对应提示

最后前端的文件列表也为空,成功删除了文件。

后端查看文件夹,发现刚上传的文件由于前端的删除操作,也对应进行了删除。

 

 五、总结

一些注意点

express应用默认端口号是3000,而案例演示的是4000(因为一般情况,3000端口容易被其他代码程序给使用用,避免这种情况,可以使用一个新的端口号(或者把占用3000端口的程序都关闭))

关于文件上传的设置,涉及到的知识点比较多,比如fs.unlink,path相关的知识,需要大家自行进行补充了解,部分知识点可以参考下方这篇博客文章。

【NODE】01-fs和path常用知识点


如果有问题,请留言评论~

如果你喜欢这篇文章,留下你的点赞和收藏~ 

 


http://www.ppmy.cn/ops/155516.html

相关文章

【memgpt】letta 课程4:基于latta框架构建MemGpt代理并与之交互

Lab 3: Building Agents with memory 基于latta框架构建MemGpt代理并与之交互理解代理状态,例如作为系统提示符、工具和agent的内存查看和编辑代理存档内存MemGPT 代理是有状态的 agents的设计思路 每个步骤都要定义代理行为 Letta agents persist information over time and…

注解(Annotation)

注解&#xff08;Annotation&#xff09;在 Java 中可以用来简化类的使用&#xff0c;使得被注解的类能够被自动发现、自动创建并在需要的地方直接调用&#xff0c;而不需要手动创建实例。具体来说&#xff0c;注解是用来标识类、方法、字段等的&#xff0c;它们通常与一些框架…

各种CNN 卷积特征图可视化理解方法(链接)

1.链接一 C/DNN Explainer CNN Explainerhttps://poloclub.github.io/cnn-explainer/ 2.Scaling Deep Learning Interpretability by Visualizing Activation and Attribution Summit: Scaling Deep Learning Interpretability by Visualizing Activation and Attribution Sum…

分层多维度应急管理系统的设计

一、系统总体架构设计 1. 六层体系架构 #mermaid-svg-QOXtM1MnbrwUopPb {font-family:"trebuchet ms",verdana,arial,sans-serif;font-size:16px;fill:#333;}#mermaid-svg-QOXtM1MnbrwUopPb .error-icon{fill:#552222;}#mermaid-svg-QOXtM1MnbrwUopPb .error-text{f…

为什么就Kafka有分区?

引言 消息队列很多&#xff0c;RocketMQ RabbitMQ ActiveMQ 多数是BrokerQuene的策略&#xff0c;本篇文章详细分析Kafka的分区技术选型的意义和作用 并发处理能力 并行处理消息&#xff1a;分区允许 Kafka 在多个分区上并行处理消息。不同的分区可以分布在不同的 Broker 节…

【数据结构】并查集

1.基本操作 void makeset(){ for(int i1;i<n;i)fa[i]i; }int findd(int x){ while(fa[x]!x)xfa[x]fa[fa[x]]; return x; }void unionn(int x,int y){ int zxfindd(x);int zyfindd(y); if(zx!zy)fa[zy]zx; }2.种类并查集 Parity Game 关押罪犯 [NOIP 2010 提高组] 关押罪…

【协议详解】卫星通信5G IoT NTN SIB33-NB 信令详解

一、SIB33信令概述 在5G非地面网络&#xff08;NTN&#xff09;中&#xff0c;卫星的高速移动性和广域覆盖特性使得地面设备&#xff08;UE&#xff09;需要频繁切换卫星以维持连接。SIB32提供了UE预测当前服务的卫星覆盖信息&#xff0c;SystemInformationBlockType33&#x…

力扣经典题目之14. 最长公共前缀

今天继续给大家分享一道力扣的做题心得今天这道题目是14. 最长公共前缀 - 力扣&#xff08;LeetCode&#xff09; 题目如下 1&#xff0c;题目分析 题目给出了一个字符串数组&#xff0c;我们需要找出这个数组中所有字符串元素的最长的公共前缀字符&#xff0c;公共前缀和即为…