Front-end vue+express file upload and download example

Front-end vue+express file upload and download example

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>

insert image description here

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)
      })
    }, 

insert image description here

(2): Front-end file download

The first method: The backend returns a download link address, which the frontend can use directly
Second method: Download using binary stream file

 <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()        
    });
  }, 

insert image description here

(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()
      })
    } 

image.png

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 Vue+axios+Node+express to realize file upload (user avatar upload)

<<:  Detailed explanation of the difference between cesllspacing and cellpadding in table

>>:  Introduction to MySQL database performance optimization

Recommend

MySQL not null constraint case explanation

Table of contents Set a not null constraint when ...

React dva implementation code

Table of contents dva Using dva Implementing DVA ...

How to install Postgres 12 + pgadmin in local Docker (support Apple M1)

Table of contents introduce Support Intel CPU Sup...

Three commonly used MySQL data types

Defining the type of data fields in MySQL is very...

Mysql query the most recent record of the sql statement (optimization)

The worst option is to sort the results by time a...

Solution to high CPU usage of Tomcat process

Table of contents Case Context switching overhead...

Introduction to Sublime Text 2, a web front-end tool

Sublime Text 2 is a lightweight, simple, efficien...

Detailed explanation of MySql automatic truncation example

Detailed explanation of MySql automatic truncatio...

Details on using JS array methods some, every and find

Table of contents 1. some 2. every 3. find 1. som...

The use of FrameLayout in six layouts

Preface In the last issue, we explained LinearLay...

Summary of MySQL5 green version installation under Windows (recommended)

1 Download MySQL Download address: http://downloa...

Implementation of docker-compose deployment of zk+kafka+storm cluster

Cluster Deployment Overview 172.22.12.20 172.22.1...

Vue Element front-end application development: Use of API Store View in Vuex

Table of contents Overview 1. Separation of front...