vue axios无法获取响应头Content-Disposition字段

vue axios无法获取响应头Content-Disposition,Content-Range等字段

默认情况下,header只有六种 simple response headers(简单响应首部)暴露给外部:

Cache-Control
Content-Language
Content-Type
Expires
Last-Modified
Pragma
暴露给外部,意思是既可以在 Network 里看到,也可以在前端代码里获取到他们的值。
目前的情况是Network 可以看到,但是axios的response拿不到Content-Disposition,Content-Range。

响应首部 Access-Control-Expose-Headers 就是控制暴露的开关,列出哪些首部可以作为响应的一部分暴露给外部。

解决办法:

private static void downLoadExcel(String fileName, HttpServletResponse response, Workbook workbook) throws IOException {
    response.setCharacterEncoding("UTF-8");
    response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
    // 配置
    response.setHeader("Access-Control-Expose-Headers", "Content-Disposition");
    response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));
    workbook.write(response.getOutputStream());
}

注意如果有配置跨域,则上面的解决方法无效:

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.reactive.CorsWebFilter;
import org.springframework.web.cors.reactive.UrlBasedCorsConfigurationSource;
import org.springframework.web.util.pattern.PathPatternParser;

/**
 * 跨域配置
 */
@Configuration
public class CorsConfig {
    private static final String ALL = "*";

    @Order(Ordered.HIGHEST_PRECEDENCE)
    @Bean
    public CorsWebFilter corsFilter() {
        CorsConfiguration config = new CorsConfiguration();
        // cookie跨域
        config.setAllowCredentials(Boolean.TRUE);
        config.addAllowedMethod(ALL);
        config.addAllowedOrigin(ALL);
        config.addAllowedHeader(ALL);
        // 配置前端js允许访问的自定义响应头
//        config.addExposedHeader("setToken");

        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource(new PathPatternParser());
        source.registerCorsConfiguration("/**", config);
        return new CorsWebFilter(source);
    }
}

转自https://blog.csdn.net/lonelymanontheway/article/details/117305087

  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值