Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to upload and download files with front-end vue+express

2025-01-22 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/02 Report--

本篇内容主要讲解"前端vue+express怎么实现文件的上传下载",感兴趣的朋友不妨来看看。本文介绍的方法操作简单快捷,实用性强。下面就让小编来带大家学习"前端vue+express怎么实现文件的上传下载"吧!

新建server.js

yarn init -yyarn add express nodemon -Dvar 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表单

Type 1: Input box

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): front-end file download

The first type: the backend returns a download link address, and the front-end can be used directly.

The second type: use binary stream file download

handleDownload() { axios({ method: 'get', url: "http://localhost:9527/download", data: { test: "test data" }, responseType: "arraybuffer" // arraybuffer is an interface provided in js to process binary }).then(response => { //Create a Blob instance with returned binary data if(! response) return; let blob = new Blob([response.data], { type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", }) // for .xlsx files //generate file path via URL.createObjectURL let url = window.URL.createObjectURL(blob) console.log("url==========",url) //Create a tag let ele = document.createElement("a") ele.style.display = 'none' //Set href attribute to file path, download attribute to file name ele.href = url ele.download = this.name //add a tag to the page and simulate clicking document.querySelectorAll("body")[0].appendChild(ele) ele.click() //remove a tag ele.remove() }); },

(3)Additional: download of binary stream pictures

//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 //Picture echo var a = document.createElement('a') a.href = src a.download = '2.jpg' a.click() a.remove() }) }

At this point, I believe everyone has a deeper understanding of "how to upload and download files in front-end vue+express," so let's actually operate it! Here is the website, more related content can enter the relevant channels for inquiry, pay attention to us, continue to learn!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report