Technology Sharing

js spring boot realizes simple front-end and back-end file download function

2024-07-12

한어Русский языкEnglishFrançaisIndonesianSanskrit日本語DeutschPortuguêsΕλληνικάespañolItalianoSuomalainenLatina

js+boot project implements custom download

1. Front-end page

1. Import the js package of axios first

2. Pay attention to the format of axios response:result.data.Real data content

3. The URL requested here is the getMapping URL of your boot project, just keep it consistent

4. If you want to set up in the backendfile name, then after the backend generates it, it will respond with a fileName field, and the front end can parse the value.

Here is js adding aa tag, call the click method to implement the code trigger jump.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <script src="js/axios.min.js"></script>
</head>
<body>
<h2>模拟下载</h2>
<button onclick="downloading()">Click me</button>
</body>
<script>
    async function downloading() {
        const result = await axios.get('http://localhost:8080/download');
        console.log(result.data)
        if (result.data.code === 200) {
            const blob = new Blob([result.data.data], {type: 'text/plain;charset=utf-8'});
            const link = document.createElement('a')
            link.style.display = 'none'
            const url = URL.createObjectURL(blob)
            link.href = url
            link.download = '文件名.txt'
            document.body.appendChild(link)
            link.click()
            document.body.removeChild(link)
            URL.revokeObjectURL(url)
        } else {
            alert("下载失败!")
        }
    }

</script>
</html>

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35

2. Backend Code

1. Most demos on the Internet return resp by settingRequest BodyHere is another way to return the data array. If it is in other formats such as Excel, you can respond and return binary data byte[].

2. If there is no pure ASCII code such as Chinese, you can set the base64 response. If there is Unicode encoding, remember not to use base64 encoding, otherwise garbled characters will be caused after the front-end atob() method.

3. Gson is used here to format the map into a json string and return it to the front end

    @GetMapping("/download")
    @ResponseBody
    public String downloadFile() {

        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < 500; i++) {
            sb.append("模拟一条数据").append(i).append("n");
        }

        Map<String, Object> resultMap = new HashMap<>(6);
        resultMap.put("code", 200);
        resultMap.put("data", sb.toString());

        return gson.toJson(resultMap);
    }


  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17

2. Project launch test

insert image description here
Project startup access: http://localhost:8080/toIndex

insert image description here
Click the button to download
insert image description here
View txt text
insert image description here

IV. Conclusion

The above is a simple demo of the file download function.
Although the front-end and back-end development here is not separated, the design concept is completely based on the back-end data transmission, and no excessive processing is done on the view, which is still very valuable for reference and learning.

I have omitted many details and only shown the essentials.
For example, your file download involves sub-package download, large file segment download, etc.
For example, generalization of download formats, etc.

I hope it can help everyone solve the problem. Please give more likes to help the blogger continue to update~
Please be gentle, it's just a simple demo for us to learn from each other.