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>
相关推荐
千叶风行10 小时前
Text-to-SQL 技术设计与注意事项
前端·人工智能·后端
软件开发技术深度爱好者10 小时前
HTML5+JavaScript读取DOCX 文档完整内容
前端·html5
幽络源小助理11 小时前
苹果CMS V10 MXPro V4.5模版下载, 自适应视频主题源码, 幽络源源码
前端·开源·源码·php源码
kyriewen11 小时前
坏了,黑客学会用AI写外挂了
前端·程序员·ai编程
xiangxiongfly91511 小时前
Vue3 根据角色权限动态加载路由
前端·javascript·vue.js·动态加载路由
达达尼昂12 小时前
Claude 多 Agent 系统:从零搭建一个 4 Agent 团队
前端·架构·ai编程
Aolith12 小时前
我是怎么把个人论坛首页性能从80分优化到100分的(附踩坑全记录)
vue.js·性能优化
容智信息13 小时前
AI Agent(智能体)的输出格式应该从 Markdown 转向 HTML吗?
前端·人工智能·rust·编辑器·html·prompt
_风满楼13 小时前
TDD 进阶:换个角度看会议室预约
前端·javascript·github
Amy_yang13 小时前
uni-app 安卓端纯前端预览 DOCX 的实现思路
前端·vue.js