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

Example code for implementing dynamic skinning with vue+element

Sometimes the theme of a project cannot satisfy e...

HTML table only displays the outer border of the table

I would like to ask a question. In Dreamweaver, I...

Example of adding multi-language function to Vue background management

Table of contents 1. First, configure the main.js...

CSS sets Overflow to hide the scroll bar while allowing scrolling

CSS sets Overflow to hide the scroll bar while al...

How to clean up the disk space occupied by Docker

Docker takes up a lot of space. Whenever we run c...

How to use default values ​​for variables in SASS

Variables defined in SASS, the value set later wi...

Mysql string interception and obtaining data in the specified string

Preface: I encountered a requirement to extract s...

A complete explanation of MySQL high availability architecture: MHA architecture

Table of contents 1. Introduction 2. Composition ...

Detailed explanation of cross-usage of Ref in React

Table of contents 1. First, let’s explain what Re...

Summary of MySQL view principles and usage examples

This article summarizes the principles and usage ...

W3C Tutorial (14): W3C RDF and OWL Activities

RDF and OWL are two important semantic web techno...

MySQL 8.0.23 installation super detailed tutorial

Table of contents Preface 1. Download MySQL from ...