SpringBoot+Vue下载txt文件

目录

一、前言

二、后端SpringBoot接口

1.跨域配置

2.Controller接口

三、前端代码

四、测试


一、前言

1.SpringBoot需要配置跨域

2.前端使用axios下载txt文件

二、后端SpringBoot接口

1.跨域配置

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;

@Configuration
public class CorsConfig {

    private CorsConfiguration buildConfig() {
        CorsConfiguration corsConfiguration = new CorsConfiguration();
        corsConfiguration.addAllowedOrigin("*");
        corsConfiguration.setAllowCredentials(true);
        corsConfiguration.addAllowedHeader("*");
        corsConfiguration.addAllowedMethod("*");
        return corsConfiguration;
    }

    @Bean
    public CorsFilter corsFilter() {
        org.springframework.web.cors.UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", buildConfig());
        return new CorsFilter(source);
    }

}

2.Controller接口

注意:不要在后端调用response.reset()方法,否则会造成跨域问题

 @RequestMapping(value = "test", method = RequestMethod.GET)
    public void exportTest(HttpServletRequest request, HttpServletResponse response) throws Exception {
        String fileName = "test.txt";
        response.setCharacterEncoding("UTF-8");
        response.setHeader("Content-disposition", "attachment;filename=" + new String(fileName.getBytes("GBK"), "iso8859-1"));
        response.setContentType("text/plain");
        PrintWriter output = response.getWriter();
        String outStream = "测试导出txt";

        for (int i = 0; i < 10; i++) {
            output.println(outStream);
        }
        output.close();
    }

三、前端代码

//导入axios组件
import axios from 'axios';
Vue.prototype.$axios = axios;

//导出方法,可以使用点击事件调用,即可导出txt文件
exportText(e) {
      console.log("点击了下载按钮exportText2");
      var url = "http://localhost:8080/export/test";
      this.$axios({
        method: "get",
        url: url,
        responseType: "blob",
        headers: {
          "Content-Type": "application/x-www-form-urlencoded",
        },
      })
        .then(function (response) {
          //下载
          var reader = new FileReader();
          reader.onload = (e) => {
            console.log("开始下载");
            //下载
            let data = response.data;
            if (!data) {
              return;
            }
            var blob = new Blob([data], {
              type: "text/plain;charset=UTF-8",
            });
            //文件名可以从header读取
            //方式一
            // var url = window.URL.createObjectURL(blob);
            // window.location.href = url;
            //方式二
            var url = window.URL.createObjectURL(blob);
            var aLink = document.createElement("a");
            aLink.style.display = "none";
            aLink.href = url;
            aLink.setAttribute("download", "test.txt");
            document.body.appendChild(aLink);
            aLink.click();
            //下载完成移除元素
            document.body.removeChild(aLink);
            //释放掉blob对象
            window.URL.revokeObjectURL(url);
          };
          reader.readAsText(response.data);
        })
        .catch(function (error) {
          console.log(error);
        });
    }

四、测试

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值