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

A simple way to achieve scrolling effect with HTML tag marquee (must read)

The automatic scrolling effect of the page can be...

Summary of the use of Vue computed properties and listeners

1. Computed properties and listeners 1.1 Computed...

mysql5.7.22 download process diagram

1. Go to the official website www.mysql.com and s...

How to automatically deploy Linux system using PXE

Table of contents Background Configuring DHCP Edi...

MYSQL slow query and log example explanation

1. Introduction By enabling the slow query log, M...

Detailed explanation of the principle of Docker image layering

Base image The base image has two meanings: Does ...

A good way to improve your design skills

So-called talent (left brain and right brain) Tha...

HTML fixed title column, title header table specific implementation code

Copy code The code is as follows: <!DOCTYPE ht...

MySQL table type storage engine selection

Table of contents 1. View the storage engine of t...

Summary of three ways to implement ranking in MySQL without using order by

Assuming business: View the salary information of...

Detailed tutorial on installing MySQL 8.0.20 database on CentOS 7

Related reading: MySQL8.0.20 installation tutoria...

Incomplete solution for using input type=text value=str

I encountered a very strange problem today. Look a...

Summary of new usage of vi (vim) under Linux

I have used the vi editor for several years, but ...