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
Preface Whether it is a stand-alone lock or a dis...
Sometimes the theme of a project cannot satisfy e...
I would like to ask a question. In Dreamweaver, I...
Table of contents 1. First, configure the main.js...
CSS sets Overflow to hide the scroll bar while al...
1. Introduction to nmon Nmon (Nigel's Monitor...
Docker takes up a lot of space. Whenever we run c...
Variables defined in SASS, the value set later wi...
Preface: I encountered a requirement to extract s...
Table of contents 1. Introduction 2. Composition ...
Table of contents 1. First, let’s explain what Re...
Due to the advantages of GTID, we need to change ...
This article summarizes the principles and usage ...
RDF and OWL are two important semantic web techno...
Table of contents Preface 1. Download MySQL from ...