使用Vue和Spring Boot实现文件下载

推荐:Vue学习汇总

使用Vue和Spring Boot实现文件下载

推荐

前端

这里介绍三种方式来实现文件下载,跨域问题在后端会进行处理,这个例子是下载MP4文件,我这里是直接使用HTML来写前端,如果用Vue来写,可能要防止mockjs对请求的responseType产生影响(mockjs会创建一个新的XMLHttpRequest对象,并且有着自己的原始配置。所以导致覆盖了axios的配置,如responseType等)。

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>download</title>
    <script src="./js/vue.js"></script>
    <script src="https://unpkg.com/axios/dist/axios.min.js"></script>
</head>
<body>
<div id="div">
    <div class="download">
        <a href="http://localhost:8081/file/download/VID_20200719_094121.mp4">download - a</a><br>
        <button @click="downloadBnt">download - window</button><br>
        <button @click="downloadReq">download - request</button>
    </div>
</div>
</body>
</html>
<script>
    var vue = new Vue({
        el: '#div',
        methods: {
            downloadBnt(){
                window.open("http://localhost:8081/file/download/VID_20200719_094121.mp4", '_blank');
            },
            downloadReq(){
                axios.get('http://localhost:8081/file/download/VID_20200719_094121.mp4',
                    {responseType: 'blob'}
                ).then((res)=>{
                    console.log('文件下载成功');
                    const blob = new Blob([res.data]);
                    const fileName = "VID_20200719_094121.mp4";

                    //对于<a>标签,只有 Firefox 和 Chrome(内核) 支持 download 属性
                    //IE10以上支持blob,但是依然不支持download
                    if ('download' in document.createElement('a')) {
                        //支持a标签download的浏览器
                        const link = document.createElement('a');//创建a标签
                        link.download = fileName;//a标签添加属性
                        link.style.display = 'none';
                        link.href = URL.createObjectURL(blob);
                        document.body.appendChild(link);
                        link.click();//执行下载
                        URL.revokeObjectURL(link.href); //释放url
                        document.body.removeChild(link);//释放标签
                    } else {
                        navigator.msSaveBlob(blob, fileName);
                    }
                }).catch((res)=>{
                    console.log('文件下载失败');
                });
            }
        }
    })
</script>

后端

@CrossOrigin注解用于解决跨域问题。

package com.kaven.system.controller;

import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.*;

@RestController
@RequestMapping("/file")
@CrossOrigin
public class FileController {

    @GetMapping("/download/{path}")
    public void download(@PathVariable("path") String path ,
                         HttpServletResponse response){
        File file = new File("C:\\Users\\Kaven\\Desktop\\images\\" + path);
        byte[] buffer = new byte[1024];
        BufferedInputStream bis = null;
        OutputStream os = null;
        try {
            //文件是否存在
            if (file.exists()) {
                //设置响应
                response.setContentType("application/octet-stream;charset=UTF-8");
                response.setCharacterEncoding("UTF-8");
                os = response.getOutputStream();
                bis = new BufferedInputStream(new FileInputStream(file));
                while(bis.read(buffer) != -1){
                    os.write(buffer);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if(bis != null) {
                    bis.close();
                }
                if(os != null) {
                    os.flush();
                    os.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

测试

第一种方法。
在这里插入图片描述
第二种方法。
在这里插入图片描述

第三种方法。
在这里插入图片描述
下载到桌面。

在这里插入图片描述
下载其他格式文件

前端改一下请求路径,下载png文件,后端不需要改。

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>download</title>
    <script src="./js/vue.js"></script>
    <script src="https://unpkg.com/axios/dist/axios.min.js"></script>
</head>
<body>
<div id="div">
    <div class="download">
        <a href="http://localhost:8081/file/download/kaven.top.png">download - a</a><br>
        <button @click="downloadBnt">download - window</button><br>
        <button @click="downloadReq">download - request</button>
    </div>
</div>
</body>
</html>
<script>
    var vue = new Vue({
        el: '#div',
        methods: {
            downloadBnt(){
                window.open("http://localhost:8081/file/download/kaven.top.png", '_blank');
            },
            downloadReq(){
                axios.get('http://localhost:8081/file/download/kaven.top.png',
                    {responseType: 'blob'}
                ).then((res)=>{
                    console.log('文件下载成功');
                    const blob = new Blob([res.data]);
                    const fileName = "kaven.top.png";

                    //对于<a>标签,只有 Firefox 和 Chrome(内核) 支持 download 属性
                    //IE10以上支持blob,但是依然不支持download
                    if ('download' in document.createElement('a')) {
                        //支持a标签download的浏览器
                        const link = document.createElement('a');//创建a标签
                        link.download = fileName;//a标签添加属性
                        link.style.display = 'none';
                        link.href = URL.createObjectURL(blob);
                        document.body.appendChild(link);
                        link.click();//执行下载
                        URL.revokeObjectURL(link.href); //释放url
                        document.body.removeChild(link);//释放标签
                    } else {
                        navigator.msSaveBlob(blob, fileName);
                    }
                }).catch((res)=>{
                    console.log('文件下载失败');
                });
            }
        }
    })
</script>

测试了视频、图片、WordExcel这四种文件格式,都是可以正常下载。

其他文件格式就不测试了。

评论中的问题

一、path为文件路径。
前端:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>download</title>
    <script src="./js/vue.js"></script>
    <script src="https://unpkg.com/axios/dist/axios.min.js"></script>
</head>
<body>
<div id="div">
    <div class="download">
        <button @click="downloadReq">download - request</button>
    </div>
</div>
</body>
</html>
<script>
    var vue = new Vue({
        el: '#div',
        methods: {
            downloadReq(){
                axios.get('http://localhost:8081/file/download',
                    {
                        params:{
                            path: 'C:/Users/Kaven/Desktop/images/VID_20200120_203552.mp4'
                        },
                        responseType: 'blob'
                    }
                ).then((res)=>{
                    console.log('文件下载成功');
                    const blob = new Blob([res.data]);
                    const fileName = "VID_20200120_203552.mp4";

                    //对于<a>标签,只有 Firefox 和 Chrome(内核) 支持 download 属性
                    //IE10以上支持blob,但是依然不支持download
                    if ('download' in document.createElement('a')) {
                        //支持a标签download的浏览器
                        const link = document.createElement('a');//创建a标签
                        link.download = fileName;//a标签添加属性
                        link.style.display = 'none';
                        link.href = URL.createObjectURL(blob);
                        document.body.appendChild(link);
                        link.click();//执行下载
                        URL.revokeObjectURL(link.href); //释放url
                        document.body.removeChild(link);//释放标签
                    } else {
                        navigator.msSaveBlob(blob, fileName);
                    }
                }).catch((res)=>{
                    console.log('文件下载失败');
                });
            }
        }
    })
</script>

后端:

package com.kaven.system.controller;

import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.*;

@RestController
@RequestMapping("/file")
@CrossOrigin
public class FileController {

    @GetMapping("/download")
    public void download(@RequestParam("path") String path ,
                         HttpServletResponse response){
        File file = new File(path);
        byte[] buffer = new byte[1024];
        BufferedInputStream bis = null;
        OutputStream os = null;
        try {
            //文件是否存在
            if (file.exists()) {
                //设置响应
                response.setContentType("application/octet-stream;charset=UTF-8");
                response.setCharacterEncoding("UTF-8");
                os = response.getOutputStream();
                bis = new BufferedInputStream(new FileInputStream(file));
                while(bis.read(buffer) != -1){
                    os.write(buffer);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if(bis != null) {
                    bis.close();
                }
                if(os != null) {
                    os.flush();
                    os.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

测试:
在这里插入图片描述
MP4文件可以正常下载,其他文件格式就不进行测试了,应该是没问题的。

二、文件名称由后端定义,并且传给前端。

前端:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>download</title>
    <script src="./js/vue.js"></script>
    <script src="https://unpkg.com/axios/dist/axios.min.js"></script>
</head>
<body>
<div id="div">
    <div class="download">
        <button @click="downloadReq">download - request</button>
    </div>
</div>
</body>
</html>
<script>
    var vue = new Vue({
        el: '#div',
        methods: {
            downloadReq(){
                axios.get('http://localhost:8081/file/download',
                    {
                        params:{
                            path: 'C:/Users/Kaven/Desktop/images/VID_20200120_203552.mp4'
                        },
                        responseType: 'blob'
                    }
                ).then((res)=>{
                    console.log('文件下载成功');

                    const blob = new Blob([res.data]);
                    // 获取文件名称
                    const fileName = res.headers['content-disposition'].split(";")[1].split("filename=")[1];
                    //对于<a>标签,只有 Firefox 和 Chrome(内核) 支持 download 属性
                    //IE10以上支持blob,但是依然不支持download
                    if ('download' in document.createElement('a')) {
                        //支持a标签download的浏览器
                        const link = document.createElement('a');//创建a标签
                        link.download = fileName;//a标签添加属性
                        link.style.display = 'none';
                        link.href = URL.createObjectURL(blob);
                        document.body.appendChild(link);
                        link.click();//执行下载
                        URL.revokeObjectURL(link.href); //释放url
                        document.body.removeChild(link);//释放标签
                    } else {
                        navigator.msSaveBlob(blob, fileName);
                    }
                }).catch((res)=>{
                    console.log('文件下载失败');
                });
            }
        }
    })
</script>
// 获取文件名称
const fileName = res.headers['content-disposition'].split(";")[1].split("filename=")[1];

后端:

package com.kaven.system.controller;

import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.*;

@RestController
@RequestMapping("/file")
@CrossOrigin
public class FileController {

    @GetMapping("/download")
    public void download(@RequestParam("path") String path ,
                         HttpServletResponse response){
        File file = new File(path);
        // 文件名称
        String filename = file.getName();
        byte[] buffer = new byte[1024];
        BufferedInputStream bis = null;
        OutputStream os = null;
        try {
            //文件是否存在
            if (file.exists()) {
                //设置响应
                response.setContentType("application/octet-stream;charset=UTF-8");
                // 将响应头中的Content-Disposition暴露出来,不然前端获取不到
                response.setHeader("Access-Control-Expose-Headers", "Content-Disposition");
                // 在响应头中的Content-Disposition里设置文件名称
                response.setHeader("Content-Disposition","attachment;filename="+filename);
                os = response.getOutputStream();
                bis = new BufferedInputStream(new FileInputStream(file));
                while(bis.read(buffer) != -1){
                    os.write(buffer);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if(bis != null) {
                    bis.close();
                }
                if(os != null) {
                    os.flush();
                    os.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
// 将响应头中的Content-Disposition暴露出来 , 不然前端获取不到
response.setHeader("Access-Control-Expose-Headers", "Content-Disposition");
// 在响应头中的Content-Disposition里设置文件名称
response.setHeader("Content-Disposition","attachment;filename="+filename);

测试:
在这里插入图片描述
在这里插入图片描述
MP4文件可以正常下载,其他文件格式就不进行测试了,应该是没问题的。

使用Vue和Spring Boot实现文件下载就介绍到这里。

写博客是博主记录自己的学习过程,如果有错误,请指正,谢谢!

评论 21
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

ITKaven

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值