java代码转发文件流,前端下载文件流

后端文件流转发代码
public static void doGetFile(HttpServletResponse httpResponse,String url) { CloseableHttpClient httpClient = null; CloseableHttpResponse response = null; byte[] result = null; try { // 通过址默认配置创建一个httpClient实例 httpClient = HttpClients.createDefault(); HttpGet httpGet = new HttpGet(url); // 设置请求头信息,鉴权 //httpGet.setHeader("Authorization", "Bearer da3efcbf-0845-4fe3-8aba-ee040be542c0"); // 设置配置请求参数 RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(35000)// 连接主机服务超时时间 .setConnectionRequestTimeout(35000)// 请求超时时间 .setSocketTimeout(60000)// 数据读取超时时间 .build(); if (summaryVer != null) { httpGet.setHeader("sd-summary-ver", summaryVer); httpGet.setHeader("sd-summary", summary); } // 为httpGet实例设置配置 httpGet.setConfig(requestConfig); // 执行get请求得到返回对象 response = httpClient.execute(httpGet); // 通过返回对象获取返回数据 HttpEntity entity = response.getEntity(); InputStream content = entity.getContent(); byte[] buffer = new byte[1024*4]; int n = 0; ServletOutputStream outputStream = httpResponse.getOutputStream(); while (-1 != (n = content.read(buffer))) { outputStream.write(buffer, 0, n); } } catch (ClientProtocolException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } finally { // 关闭资源 if (null != response) { try { response.close(); } catch (IOException e) { e.printStackTrace(); } } if (null != httpClient) { try { httpClient.close(); } catch (IOException e) { e.printStackTrace(); } } } }

前端代码
function downloadFile() {
const xhr = new XMLHttpRequest();
xhr.open('POST', 'url(下载接口地址)', true);
xhr.responseType = "blob";
xhr.onload = () => {
    openProgressBar("close", true, "下载");
    const blob = xhr.response;
    const blobUrl = URL.createObjectURL(blob);
    const a = document.createElement('a');
    a.style.display = 'none';
    a.download="数据列表.xls"
    a.href = blobUrl;
    a.target = '_blank';
    a.click();
}
var params2 = {"flowType":3,"pageNum":1,"pageSize":10}
xhr.setRequestHeader("Content-Type","application/json;charset=UTF-8");
xhr.send(JSON.stringify(params2));
}
posted @ 2023-02-24 18:07  张安东  阅读(218)  评论(0编辑  收藏  举报