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);
        });
    }

四、测试

猜你喜欢

转载自blog.csdn.net/cs373616511/article/details/114108455