Spring Boot - axios download file(带请求头下载、预览 PDF 文件,非前后端分离)

项目

新建 Spring Starter Project,编辑 pom.xml 文件,引入依赖:

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.3.3.RELEASE</version>
        <relativePath /> <!-- lookup parent from repository -->
    </parent>
    
    <groupId>com.mk</groupId>
    <artifactId>spring-boot-axios-download-file</artifactId>
    <version>1.0.0</version>
    
    <name>spring-boot-axios-download-file</name>
    
    <properties>
        <java.version>1.8</java.version>
    </properties>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
            <scope>runtime</scope>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-configuration-processor</artifactId>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>

        <!-- Commons IO -->
        <dependency>
            <groupId>commons-io</groupId>
            <artifactId>commons-io</artifactId>
            <version>2.6</version>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <configuration>
                    <excludes>
                        <exclude>
                            <groupId>org.springframework.boot</groupId>
                            <artifactId>spring-boot-configuration-processor</artifactId>
                        </exclude>
                        <exclude>
                            <groupId>org.projectlombok</groupId>
                            <artifactId>lombok</artifactId>
                        </exclude>
                    </excludes>
                </configuration>
            </plugin>
        </plugins>
    </build>

</project>

IndexController 控制器:

package com.mk.controller;

import java.io.File;
import java.io.IOException;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.io.FileUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;

@Controller
public class IndexController {

    @GetMapping({"", "/index"})
    public String index() {
        return "index";
    }
    
    @GetMapping("/download")
    public void download(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String authorization = request.getHeader("Authorization");
        System.out.println(authorization);
        
        byte[] bytes = FileUtils.readFileToByteArray(new File("E:/stm32/w25q128fv rev.m 05132016 kms.pdf"));
        
        ServletOutputStream os = response.getOutputStream();
        
        response.setHeader("Content-Type", "application/pdf");
        
        os.write(bytes);
        os.flush();
        os.close();
    }
}

启动类:

package com.mk;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class Application {

    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }
}

src/main/resources/templates/index.html 文件:

<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8">
        <title>Download File</title>
    </head>
    <body>
        <input type="button" id="download" value="download" />
        <input type="button" id="preview" value="preview" />
        <br />
        <iframe width="100%" height="500"></iframe>

        <script type="text/javascript" src="/js/axios.min.js"></script>
        <script type="text/javascript">
            window.onload = (event) => {
                const downloadButton = document.getElementById('download')
                const previewButton = document.getElementById('preview')
                const iframe = document.querySelector('iframe')
                
                downloadButton.onclick = function(event) {
                    const url = '/download'
                    const method = 'GET'
                    const headers = { 'Authorization': '1234567890' }
                    const responseType = 'blob'
                    axios({
                        url, method, headers, responseType
                    }).then(response => {
                        console.log(response)
                        
                        const blob = response.data
                        const objectURL = URL.createObjectURL(blob)
                                                    
                        const a = document.createElement('a')
                        a.href = objectURL
                        a.download = "123.pdf"
                        a.click()
                        
                        URL.revokeObjectURL(objectURL)
                    }).catch(error => console.error(error))
                }
                
                previewButton.onclick = function(event) {
                    const url = '/download'
                    const method = 'GET'
                    const headers = { 'Authorization': '1234567890' }
                    const responseType = 'blob'
                    axios({
                        url, method, headers, responseType
                    }).then(response => {
                        console.log(response)
                        
                        const blob = response.data
                        const objectURL = URL.createObjectURL(blob)
                        
                        iframe.setAttribute('src', objectURL)
                                                    
                        URL.revokeObjectURL(objectURL)
                    }).catch(error => console.error(error))
                }
            }
        </script>
    </body>
</html>

参考

axios

posted @ 2021-04-16 00:37  heismk  阅读(457)  评论(0编辑  收藏  举报