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

How to use the realip module in Nginx basic learning

Preface There are two types of nginx modules, off...

Page Refactoring Skills - Javascript, CSS

About JS, CSS CSS: Stylesheet at the top Avoid CS...

Pessimistic locking and optimistic locking in MySQL

In relational databases, pessimistic locking and ...

Docker deployment of Kafka and Spring Kafka implementation

This article mainly introduces the deployment of ...

Vue3 compilation process-source code analysis

Preface: Vue3 has been released for a long time. ...

A brief discussion on the semantics of HTML and some simple optimizations

1. What is semanticization? Explanation of Bing D...

Detailed explanation of the use and precautions of crontab under Linux

Crontab is a command used to set up periodic exec...

Detailed explanation of system input and output management in Linux

Management of input and output in the system 1. U...

MySQL trigger usage scenarios and method examples

trigger: Trigger usage scenarios and correspondin...

Detailed explanation of vue simple notepad development

This article example shares the specific code of ...

In-depth analysis of MySQL indexes

Preface We know that index selection is the work ...

Detailed steps to install Docker 1.8 on CentOS 7

Docker supports running on the following CentOS v...

Causes and solutions for MySQL master-slave synchronization delay

For historical reasons, MySQL replication is base...