Create a new 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"); //Specify the path var app = express(); app.use(express.json()); app.use(express.urlencoded({ extended: true })); // Front-end solves cross-domain issues app.all("*", (req, res, next) => { res.header("Access-Control-Allow-Origin", "*"); next(); }); // Access static resources app.use(express.static(path.join(__dirname))); // File upload app.post("/upload", multer({ dest: "./public" }).any(), (req, res) => { const { fieldname, originalname } = req.files[0]; // Create a new path 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: "Upload failed", data: [] }); } else { res.send({ code: 1, msg: "Upload successful", data: newName }); } }); }); // File download app.get('/download', function(req, res) { res.download('./public/test.xls'); }); // Image download app.get('/download/img', function(req, res) { res.download('./public/2.jpg'); }); let port = 9527; app.listen(port, () => console.log(`Port started: http://localhost:${port}`)); (1): Front-end file upload request The first type: form <form action="http://localhost:9527/upload" method="POST" encType="multipart/form-data"> <input type="file" name="user"/> <input type="submit" /> </form> The first type: input box <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): Front-end file download The first method: The backend returns a download link address, which the frontend can use directly <input type="button" value="Click to download" @click="handleDownload"> handleDownload() { axios({ method: 'get', url: "http://localhost:9527/download", data: { test: "test data" }, responseType: "arraybuffer" // arraybuffer is an interface for processing binary in js}).then(response => { // Create a Blob instance with the 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 through 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 the href attribute to the file path, and the download attribute to the file name ele.href = url ele.download = this.name // Add the a tag to the page and simulate a click document.querySelectorAll("body")[0].appendChild(ele) ele.click() // Remove the a tag ele.remove() }); }, (3) Additional: Downloading binary stream images // Download binary stream image file 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 // Image display var a = document.createElement('a') a.href = src a.download = '2.jpg' a.click() a.remove() }) } This concludes this article about the front-end vue+express implementation of file upload and download examples. For more related vue express file upload and download content, please search 123WORDPRESS.COM's previous articles or continue to browse the following related articles. I hope everyone will support 123WORDPRESS.COM in the future! You may also be interested in:
|
<<: Detailed explanation of the difference between cesllspacing and cellpadding in table
>>: Introduction to MySQL database performance optimization
The automatic scrolling effect of the page can be...
1. Computed properties and listeners 1.1 Computed...
1. Go to the official website www.mysql.com and s...
Table of contents Background Configuring DHCP Edi...
Verification environment: [root@~~/]# rpm -qa | g...
1. Introduction By enabling the slow query log, M...
Base image The base image has two meanings: Does ...
So-called talent (left brain and right brain) Tha...
Copy code The code is as follows: <!DOCTYPE ht...
Table of contents 1. View the storage engine of t...
Assuming business: View the salary information of...
Related reading: MySQL8.0.20 installation tutoria...
I encountered a very strange problem today. Look a...
Web page encoding is translated into English as we...
I have used the vi editor for several years, but ...