Vue axios cannot get response header Content-Disposition, Content-Range and other fields
By default, the header only has six simple response headers (simple response headers) exposed to the outside:
Cache-Control
Content-Language
Content-Type
Expires
Last-Modified
Pragma
is exposed to the outside, which means that it can be seen in the Network, and their values can be obtained in the front-end code.
The current situation is that the Network can be seen, but the response of axios cannot get Content-Disposition, Content-Range.
The response header Access-Control-Expose-Headers is the switch to control exposure, listing which headers can be exposed to the outside as part of the response.
Solution:
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());
}
Note that if there is cross-domain configuration, the above solution will not work:
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);
}
}
Reposted from https://blog.csdn.net/lonelymanontheway/article/details/117305087