Vue前端如何配合SpringBoot后端实现文件下载

从HTML页面下载文件是非常简单的,直接向后端发起请求,后端处理请求就可以了;但是如果前端使用Vue开发,那么实现文件下载就有些曲折:Vue前端本身作为服务端存在,为了实现下载就需要将请求通过代理转到后端服务器,后端服务器将文件响应给Vue前端服务器,Vue前端服务器再实现下载,具体实现如下:

后端代码:

java 复制代码
package com.soft.backend;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.InputStream;
import java.nio.file.Files;

@Controller
@RequestMapping("/api/file")
public class FileController {

    @RequestMapping("/download")
    public void download(String fileName, HttpServletResponse response) throws Exception {
        ServletOutputStream out = null;
        ByteArrayOutputStream baos = null;
        try {
            //通过输入流获取图片数据
            InputStream inStream = Files.newInputStream(new File("D:\\1.mp4").toPath());
            byte[] buffer = new byte[1024];
            baos = new ByteArrayOutputStream();
            int len;
            while ((len = inStream.read(buffer)) != -1) {
                baos.write(buffer, 0, len);
            }
            response.addHeader("Content-Disposition", "attachment;filename=" + new String(fileName.getBytes("utf-8"),"iso-8859-1"));
            response.addHeader("Content-Length", "" + baos.size());
            response.setHeader("filename", fileName);
            response.setContentType("application/octet-stream");
            out = response.getOutputStream();
            out.write(baos.toByteArray());
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            baos.flush();
            baos.close();
            out.flush();
            out.close();
        }
    }
}

前端代码:

vue 复制代码
<template>
	<div>
		<button type="button" @click="download">下载</button>
	</div>
</template>
<script>
	import axios from 'axios'
	export default {
		name: 'App',
		methods: {
			download() {
				var fileName="视频.mp4";
				axios(`/api/file/download`, {
					headers: {
						'Authorization': 'Bearer ' + sessionStorage.getItem('token'),
						'Content-Type': 'application/octet-stream'
					},
					methods: 'get',
					params: {
						fileName: fileName,
					},
					responseType: 'blob'
				}).then((res) => {
					if (res.status === 200) {
						const content = res.data
						const blob = new Blob([content])
						if ('download' in document.createElement('a')) { // 非IE下载
							const elink = document.createElement('a') // 创建一个a标签通过a标签的点击事件区下载文件
							elink.download = fileName
							elink.style.display = 'none'
							elink.href = URL.createObjectURL(blob) // 使用blob创建一个指向类型数组的URL
							document.body.appendChild(elink)
							elink.click()
							URL.revokeObjectURL(elink.href) // 释放URL 对象
							document.body.removeChild(elink)
						} else { // IE10+下载
							navigator.msSaveBlob(blob, fileName)
						}
					}
				}).catch(res => {
					console.log(res)
				})
			}
		}
	}
</script>
相关推荐
笨笨饿8 小时前
#121_图传中的H.364编码与MP4的联系
linux·运维·前端·单片机·嵌入式硬件·面试·职场和发展
默_笙8 小时前
☕ 我给 TS 类型做了台"瘦身手术",还顺手用 Docker 起了个 MySQL
前端·javascript
leoZ2319 小时前
AI+前端提效- 06 AI辅助调试排错:前端报错、白屏、兼容问题极速定位
前端·人工智能·chatgpt·状态模式·超分辨率重建·openvino·dreamfusion
李昊哲小课9 小时前
SpringBoot4 云端咖啡站 阶段五:交付与进阶
人工智能·spring boot·大模型·log4j·智能体
ji_shuke9 小时前
Vue 3 使用 History 哨兵和 popstate 拦截浏览器返回
前端·javascript·vue.js·history·哨兵·popstate
名字还没想好☜10 小时前
Prometheus 告警实战:写 alerting rules、用 Alertmanager 做路由分组与抑制
运维·前端·javascript·docker·kubernetes·prometheus
郭邯10 小时前
从零撸了一个 HTML 实体编解码工具,顺便聊聊我和 AI 结对编程的日常
前端
MetaLite10 小时前
SpringBoot分页接口怎么设计-pageSize不设上限会发生什么
java·spring boot·后端
樊小肆10 小时前
DeepSeeker-Code源码导读12-Hooks四引擎
前端·人工智能·agent
xiaohe060110 小时前
🤔 v-mortal 是什么?!我只知道 v-model 啊!
vue.js·vite·前端工程化