前端vue+express实现文件的上传下载示例
作者:lxslxskxs 时间:2024-05-13 09:12:03
新建server.js
yarn init -y
yarn add express nodemon -D
var express = require("express");
const fs = require("fs");
var path = require("path");
const multer = require("multer"); //指定路径的
var app = express();
app.use(express.json());
app.use(express.urlencoded({ extended: true }));
// 前端解决跨域问题
app.all("*", (req, res, next) => {
res.header("Access-Control-Allow-Origin", "*");
next();
});
// 访问静态资源
app.use(express.static(path.join(__dirname)));
// 文件上传
app.post("/upload", multer({ dest: "./public" }).any(), (req, res) => {
const { fieldname, originalname } = req.files[0];
// 创建一个新路径
const name = fieldname.slice(0, fieldname.indexOf("."));
const newName = "public/" + name + path.parse(originalname).ext;
fs.rename(req.files[0].path, newName, function (err) {
if (err) {
res.send({ code: 0, msg: "上传失败", data: [] });
} else {
res.send({ code: 1, msg: "上传成功", data: newName });
}
});
});
// 文件下载
app.get('/download', function(req, res) {
res.download('./public/test.xls');
});
// 图片下载
app.get('/download/img', function(req, res) {
res.download('./public/2.jpg');
});
let port = 9527;
app.listen(port, () => console.log(`端口启动: http://localhost:${port}`));
(1):前端文件上传请求
第一种: form表单
<form action="http://localhost:9527/upload" method="POST" encType="multipart/form-data">
<input type="file" name="user"/>
<input type="submit" />
</form>
第一种: input输入框
<input type="file" @change="changeHandler($event)"/>
changeHandler(event) {
let files = event.target.files[0];
console.log("files",files)
let data = new FormData();
data.append(files.name,files);
console.log("data",data)
axios.post("http://localhost:9527/upload",data,{
headers:{
"Content-Type":"multipart/form-data"
}
}).then(res =>{
console.log("res",res)
})
},
(2):前端文件下载
第一种: 后端返回一个下载的链接地址,前端直接使用 即可
第二种: 使用二进制流文件下载
<input type="button" value="点击下载" @click="handleDownload">
handleDownload() {
axios({
method: 'get',
url: "http://localhost:9527/download",
data: {
test: "test data"
},
responseType: "arraybuffer" // arraybuffer是js中提供处理二进制的接口
}).then(response => {
// 用返回二进制数据创建一个Blob实例
if(!response) return;
let blob = new Blob([response.data], {
type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
}) // for .xlsx files
// 通过URL.createObjectURL生成文件路径
let url = window.URL.createObjectURL(blob)
console.log("url==========",url)
// 创建a标签
let ele = document.createElement("a")
ele.style.display = 'none'
// 设置href属性为文件路径,download属性可以设置文件名称
ele.href = url
ele.download = this.name
// 将a标签添加到页面并模拟点击
document.querySelectorAll("body")[0].appendChild(ele)
ele.click()
// 移除a标签
ele.remove()
});
},
(3) 附加:二进制流图片的下载
// 二进制流图片文件的下载
downLoadImg() {
axios({
method: 'get',
url: `http://localhost:9527/download/img`,
responseType: 'arraybuffer',
params: {
id: 12
}
}).then(res => {
var src = 'data:image/jpg;base64,' + btoa(new Uint8Array(res.data).reduce((data, byte) => data + String.fromCharCode(byte), ''))
// this.srcImg = src // 图片回显
var a = document.createElement('a')
a.href = src
a.download = '2.jpg'
a.click()
a.remove()
})
}
来源:https://blog.csdn.net/lxs19930928/article/details/122192837
标签:vue,expres,上传,下载
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
pytorch 中forward 的用法与解释说明
2021-08-10 04:14:44
Caffe卷积神经网络视觉层Vision Layers及参数详解
2023-02-28 02:06:41
![](https://img.aspxhome.com/file/2023/5/84985_0s.png)
获取Dom元素的X/Y坐标
2009-10-10 12:49:00
![](https://img.aspxhome.com/file/UploadPic/200910/10/123-57s.gif)
CentOS下安装MySQL5.6.10和安全配置教程详解
2024-01-24 08:28:26
python执行等待程序直到第二天零点的方法
2023-08-27 11:49:21
php实现的CSS更新类实例
2023-11-21 22:28:30
基于Python的身份证验证识别和数据处理详解
2021-04-22 04:43:09
![](https://img.aspxhome.com/file/2023/0/89200_0s.png)
Discuz7 的提示效果如何实现
2010-01-13 13:10:00
![](https://img.aspxhome.com/file/UploadPic/20101/13/2010113131444838s.jpg)
如何使用python中的networkx来生成一个图
2022-08-13 05:13:32
![](https://img.aspxhome.com/file/2023/3/101663_0s.png)
Python中Yield的基本用法
2021-08-30 15:34:55
SQL查询排名函数实例
2024-01-22 13:14:10
![](https://img.aspxhome.com/file/2023/3/91153_0s.jpg)
基于Python实现二维图像双线性插值
2023-08-13 07:46:45
![](https://img.aspxhome.com/file/2023/4/61984_0s.png)
如何使用Goland IDE go mod 方式构建项目
2024-02-23 00:36:40
![](https://img.aspxhome.com/file/2023/3/109693_0s.png)
Pycharm报错:'NoneType' object has no attribute 'bytes'的解决方法
2023-06-19 19:46:46
![](https://img.aspxhome.com/file/2023/0/135100_0s.png)
Python操作word常见方法示例【win32com与docx模块】
2022-09-22 13:12:33
MAC下Mysql5.7.10版本修改root密码的方法
2024-01-27 00:05:58
浅析Python+OpenCV使用摄像头追踪人脸面部血液变化实现脉搏评估
2023-08-05 18:46:48
![](https://img.aspxhome.com/file/2023/9/117599_0s.jpg)
SQL建立数据库及删除数据库命令
2024-01-13 01:58:16
php比较两个指定的日期的实例讲解
2023-06-13 12:11:29
asp如何获知页面上的图象的实际尺寸?
2009-11-24 20:50:00