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

Vue-Router installation process and principle detailed

Table of contents 1. Front-end routing implementa...

Introduction to TypeScript basic types

Table of contents 1. Basic types 2. Object Type 2...

Example of troubleshooting method to solve Nginx port conflict

Problem Description A Spring + Angular project wi...

Share CSS writing standards and order [recommended for everyone to use]

CSS writing order 1. Position attributes (positio...

Docker exposes port 2375, causing server attacks and solutions

I believe that students who have learned about th...

JavaScript removes unnecessary properties of an object

Table of contents Example Method 1: delete Method...

Use label tag to select the radio button by clicking the text

The <label> tag defines a label (tag) for an...

Pure CSS to achieve three-dimensional picture placement effect example code

1. Percentage basis for element width/height/padd...

Some notes on mysql self-join deduplication

Let me briefly explain the functional scenario: T...

How to implement Linux deepin to delete redundant kernels

The previous article wrote about how to manually ...

Sample code for installing ElasticSearch and Kibana under Docker

1. Introduction Elasticsearch is very popular now...

The past two years with user experience

<br />It has been no more than two years sin...

Linux uses binary mode to install mysql

This article shares the specific steps of install...

Summary of English names of Chinese fonts

When using the font-family property in CSS to ref...