前后端分离项目文件下载的正确姿势

场景:前端需要下载后端文件,并且需要给个参数id来下载某个记录的文件

以前不带参数不用token时,可以直接用a标签调用get请求,但现在需要加参数和请求头,a标签无法实现,笔者后来采用button触发js方法,调用接口,但最后的效果就是,后端的响应流返回不到前端的浏览器!!!

所以,只能前端模拟a标签
特此记录

效果图:
在这里插入图片描述

一、前端代码

还是正常的按钮

  <el-button @click="clickCall('handleExport', scope)">导出</el-button>
import Cookie from "js-cookie";
import axios from "axios";
import Domain from "../../../api/domain";
const URL_DOMAIN = `${Domain.domain}`;
    // 文件下载操作
    handleExport(row) {
      axios
        .get(`${URL_DOMAIN}` + "/biz/master/route/exportXml?id=" + row.id, {
          responseType: "blob",
          headers: { Authorization: Cookie.get("droneToken") },
        })
        .then((res) => {
          var elink = document.createElement("a");
          elink.download = "飞行路径.xml";
          elink.style.display = "none";
          elink.href = window.URL.createObjectURL(res.data);
          elink.click();
          this.$message({
            type: "success",
            message: "数据导出成功",
          });
        })
        .catch((err) => {
          this.$message.error(`数据导出失败,${err.message}`);
        });
    },

二、后端代码

Controller层

    @ApiOperation("导出XML数据")
    @GetMapping("exportXml")
    public void exportData(HttpServletResponse response,@RequestParam(value="id")Long id) throws Exception {
          routeService.exportData(response,id);
    }

Service层

    @Override
    public void exportData(HttpServletResponse response, Long id)  {
        Blob blob = getXmlFile(id);
        byte[] buf = new byte[1024 * 5];
        try(OutputStream output = response.getOutputStream(); InputStream is = blob.getBinaryStream()){
            response.reset();
            //设置响应头,
            response.setHeader("Content-disposition", "attachment; filename=temp.xml");
            response.setContentType("application/xml");
            System.out.println("输出内容");
            while (is.read(buf) > 0) {
                String s = new String(buf);
                output.write(s.getBytes(), 0, s.length());
            }
            System.out.println("输出内容");
            output.flush();
        } catch (SQLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    Blob getXmlFile(Long id) {
        Connection connection = null;
        PreparedStatement ps = null;
        Blob blob = null;
        try {
            connection = new JDBCConnection().getConnection();
            String sql = "select * from tb_route where id=?";
            ps = connection.prepareStatement(sql);
            ps.setLong(1, id);
            //获取到数据库中的二进制数据
            ResultSet rs = ps.executeQuery();
            rs.next();
            blob = rs.getBlob("file_txt");
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            try {
                if (!connection.isClosed()) {
                    connection.close();
                }
            } catch (SQLException e) {
                e.printStackTrace();
            }
            try {
                if (!ps.isClosed()) {
                    ps.close();
                }
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        return blob;
    }
  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
要实战下载一个基于Spring Boot和Vue 3的大型前后端分离项目,可以按照以下步骤进行: 1. 确保你已经安装了相关的开发环境,包括Java开发环境和Node.js环境。可以在官方网站上下载并安装最新版本的JDK和Node.js。 2. 打开终端或命令行界面,并通过npm安装Vue CLI(Vue Command Line Interface)。在终端中运行以下命令: ``` npm install -g @vue/cli ``` 3. 创建一个新的Vue 3项目。在终端中运行以下命令: ``` vue create my-project ``` 根据提示选择使用Vue 3版本和一些其他配置选项。 4. 进入项目目录。在终端中运行以下命令: ``` cd my-project ``` 5. 开发前端。通过Vue CLI提供的开发服务器,在本地运行前端项目并进行开发。在终端中运行以下命令: ``` npm run serve ``` 这将启动开发服务器,并提供一个本地地址,例如:http://localhost:8080。在浏览器中打开此地址,你将看到默认生成的Vue欢迎页面。 6. 下载Spring Boot后端项目。可以在GitHub等代码托管平台上搜索和下载基于Spring Boot的后端项目模板。选择一个合适的项目,下载并解压缩。 7. 在IDE(如IntelliJ IDEA)中打开后端项目。将此项目导入你的IDE,并按照需要进行配置和修改。 8. 运行后端项目。通过IDE的运行按钮或在终端中运行以下命令启动后端项目: ``` ./mvnw spring-boot:run ``` 后端项目将启动,并监听默认端口8080。 9. 在Vue前端项目中配置跨域访问。由于前后端分离前端将运行在不同的域上,需要配置后端允许跨域访问。在Vue项目的src目录下创建一个vue.config.js文件,并在其中添加以下代码: ```javascript module.exports = { devServer: { proxy: { '/api': { target: 'http://localhost:8080', ws: true, changeOrigin: true } } } } ``` 10. 在前端项目中发起API请求。根据后端项目的API文档,在前端项目代码中编写对后端接口的调用。可以使用Vue提供的axios等HTTP库来发送请求。 通过以上步骤,你就可以开始在本地开发一个基于Spring Boot和Vue 3的大型前后端分离项目实战。根据实际需求,你可以进一步完善前后端的交互和功能。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值