Spring Boot - XMLHttpRequest Download(带请求头下载、预览 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-XMLHttpRequest-download</artifactId>
    <version>1.0.0</version>
    
    <name>spring-boot-XMLHttpRequest-download</name>
    <description>Demo project for Spring Boot</description>
    
    <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>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
            <exclusions>
                <exclusion>
                    <groupId>org.junit.vintage</groupId>
                    <artifactId>junit-vintage-engine</artifactId>
                </exclusion>
            </exclusions>
        </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();
    }
}

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

<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8">
        <title>Using XMLHttpRequest</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">
            window.onload = (event) => {
                const downloadButton = document.getElementById('download')
                const previewButton = document.getElementById('preview')
                const iframe = document.querySelector('iframe')
                
                downloadButton.onclick = function(event) {
                    const xhr = new XMLHttpRequest()
                    xhr.addEventListener("load", function(event) {
                        console.log(event)
                        if (xhr.readyState == 4 && xhr.status == 200) {
                            const blob = xhr.response
                            const objectURL = URL.createObjectURL(blob)
                                                        
                            const a = document.createElement('a')
                            a.href = objectURL
                            a.download = "123.pdf"
                            a.click()
                            
                            URL.revokeObjectURL(objectURL)
                        }
                    })
                    xhr.open('GET', '/download', true)
                    xhr.responseType = 'blob'
                    xhr.setRequestHeader('Authorization', '1234567890')
                    xhr.send()
                }
                
                previewButton.onclick = function(event) {
                    const xhr = new XMLHttpRequest()
                    xhr.addEventListener("load", function(event) {
                        console.log(event)
                        if (xhr.readyState == 4 && xhr.status == 200) {
                            const blob = xhr.response
                            const objectURL = URL.createObjectURL(blob)
                            
                            iframe.setAttribute('src', objectURL)
                                                        
                            URL.revokeObjectURL(objectURL)
                        }
                    })
                    xhr.responseType = 'blob'
                    xhr.open('GET', '/download', true)
                    xhr.setRequestHeader('Authorization', '1234567890')
                    xhr.send()
                }
            }
        </script>
    </body>
</html>

参考

XMLHttpRequest

前端处理文件下载(带请求头)

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