Ajax请求导出(下载)文件

最近做文件导出,由于登录认证方式改为oauth方式,请求后台导出接口需要设置请求头。所以传统的通过form提交的方式并不能满足需求,故而通过原生ajax的方式来实现。

1.实现前端html




    
    测试export
    
    


    

2.后台response加入头信息

public ExportExcel writeWithAjaxHeader(HttpServletResponse response, String fileName) throws IOException{
		//response.reset();
		ServletContext context = RequestContextUtils.getCurrentRequest().getServletContext();
	    String mimeType = context.getMimeType(fileName);
	    String fName = ConverterUtil.toDownloadName(URLEncoder.encode(fileName, "utf8"));
       
	    response.addHeader("Access-Control-Expose-Headers", "ajax-mimeType, ajax-filename");
        response.setHeader("Content-Disposition", "attachment; filename="+fName);
        response.setHeader("ajax-mimeType", mimeType);
        response.setHeader("ajax-filename", fName);
        response.setContentType("application/octet-stream; charset=utf-8");
		write(response.getOutputStream());
		return this;
	}

你可能感兴趣的:(javascript)