Vue implements zip file download

Vue implements zip file download

This article example shares the specific code of Vue to download zip files for your reference. The specific content is as follows

el-button

<el-button size="mini" type="success" @click="downloadHandle(fileName, fileLocation)">Download</el-button>

js processing instructions

request interceptor request.js

Axios is introduced and an axios instance is created, and a request interceptor is added

import axios from 'axios'


// Create an axios instance const service = axios.create({
  baseURL: '', // baseURL of the api
  timeout: 20000, // request timeout params: {
 // Request parameters}
});

// request interceptor service.interceptors.request.use(config => {
  // .... config add processing......
  
  return config
}

export default service

The request interceptor is processed before the request and can add http headers settings, for example:

1. HTTP Request Headers: token, cookie, session and other values ​​are added (config.headers['backend value name'] = 'related value';):

(1) config.headers['token'] = 'token value';
(2) config.headers['cookie'] = 'cookie value';
(3) config.headers['session'] = 'session value';

2. Headers post settings: such as Content-Type

To upload a file, use: config.headers.post['Content-Type'] = 'multipart/form-data';

Download zip file

1. request.js code:

import axios from 'axios'


// Create an axios instance const service = axios.create({
  baseURL: '', // baseURL of the api
  timeout: 20000, // request timeout params: {
 // Request parameters}
});

// request interceptor service.interceptors.request.use(config => {
  // config add token value config.headers['token'] = getToken(); // getToken() is my value acquisition method, system verification uses return config
}

export default service

2. Vue page references request.js

import request from '@/utils/request'

Download Processing

// fileName download setting name, fileLocation file storage name downloadHandle(fileName,fileLocation) {
   let prome = {
     fileLocation: fileLocation
   }
   request.post(
    '/api/downloadFile', 
    prome, 
    {
      responseType: 'blob',
      timeout: 60000
    }
   ).then(response => {
     if (!response.size) {
       this.$message({
         message: 'No file available for download',
         type: 'warning'
       })
       return
     }
     const url = window.URL.createObjectURL(new Blob([response]))
     const link = window.document.createElement('a')
     link.style.display = 'none'
     link.href = url
     link.setAttribute('download', fileName+'.zip')
     document.body.appendChild(link)
     link.click()
   }).catch((data) => {
     console.log(data)
   })
},

Background Processing

Processed by the Java API based on the request /api/downloadFile

package com.web.controller;

import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.util.Map;

@RestController
@RequestMapping("/api")
public class DownloadFileDemo {

    /**
     * File download * @param tranNap
     * @param request
     * @param response
     */
    @RequestMapping(value = "/downloadFile")
    public void downloadFile(@RequestBody Map<String, Object> tranNap, HttpServletRequest request, HttpServletResponse response) {
        String fileLocation = tranNap.get("fileLocation")+"";
        try {
            String filePath = "D:/file/" + fileLocation + ".zip";
            //Get the file File file = new File(filePath);
            if (!file.exists()) {
                System.out.println("[File Download] No file available for download");
                return;
            }
            FileInputStream fileInputStream = new FileInputStream(file);
            //Set the Http response header to tell the browser to download the file name Filename
            response.setHeader("Content-Disposition", "attachment;Filename=" + URLEncoder.encode(fileLocation+".zip", "UTF-8"));
            OutputStream outputStream = response.getOutputStream();
            byte[] bytes = new byte[2048];
            int len ​​= 0;
            while ((len = fileInputStream.read(bytes)) > 0) {
                outputStream.write(bytes, 0, len);
            }
            fileInputStream.close();
            outputStream.close();
        } catch (Exception e) {
            System.out.println("[File download] Download file exception");
            e.printStackTrace();
            return;
        }
    }

}

The above is the full content of this article. I hope it will be helpful for everyone’s study. I also hope that everyone will support 123WORDPRESS.COM.

You may also be interested in:
  • Vue implements the function of clicking a button to download files
  • How to download files and determine status in VUE
  • Tutorial on how to batch download files/pictures in zip using Vue
  • Summary of three ways to download files in front-end vue

<<:  How to install docker on ubuntu20.04 LTS

>>:  How to install WSL2 Ubuntu20.04 on Windows 10 and set up the docker environment

Recommend

A brief discussion on whether CSS will block page rendering

Maybe everyone knows that js execution will block...

Vue implements infinite loading waterfall flow

This article example shares the specific code of ...

How to implement Nginx reverse proxy for multiple servers

Nginx reverse proxy multiple servers, which means...

Deploy Nginx+Flask+Mongo application using Docker

Nginx is used as the server, Mongo is used as the...

Eight implementation solutions for cross-domain js front-end

Table of contents 1. jsonp cross-domain 2. docume...

Vue implements an example of pulling down and scrolling to load data

Table of contents Step 1: Installation Step 2: Ci...

JavaScript to implement click to switch verification code and verification

This article shares the specific code of JavaScri...

Solution to the cross-domain problem of SpringBoot and Vue interaction

Table of contents Browser Same Origin Policy 1. V...

Detailed graphic explanation of MySql5.7.18 character set configuration

Background: A long time ago (2017.6.5, the articl...

How to install MySQL 5.7.29 with one click using shell script

This article refers to the work of 51CTO blog aut...

XHTML Basic 1.1, a mobile web markup language recommended by W3C

W3C recently released two standards, namely "...

Detailed explanation of the WeChat applet request pre-processing method

question Because some of our pages request data i...

VMware installation of Ubuntu 20.04 operating system tutorial diagram

Memo: Just experience it. Record: NO.209 This exa...