实现文件下载功能
这里提供了下载的方法,希望能帮到你。
/**
* 前端下载文件
*
* @param response
* @param fileName 文件名称
* @param filePath 文件路径
*/
public static void download(HttpServletResponse response, String fileName, String filePath) throws Exception {
BufferedOutputStream bos = null;
InputStream content = null;
FileInputStream fileInputStream = null;
response.reset();
try {
response.setHeader("Access-Control-Allow-Origin", "*");
response.setHeader("Access-Control-Allow-Methods", "*");
response.setHeader("Access-Control-Max-Age", "3600");
response.setHeader("Access-Control-Allow-Headers", "*");
response.setHeader("Content-Disposition", "attachment;filename="
+ URLEncoder.encode(fileName, "UTF-8"));
response.setContentType("application/x-download;charset=UTF-8");
HttpGet http = new HttpGet(filePath);
CloseableHttpClient httpClient = HttpClients.custom().build();
CloseableHttpResponse closeableHttpResponse = httpClient.execute(http);
//获取响应HttpEntity对象
HttpEntity httpEntity = closeableHttpResponse.getEntity();
response.setHeader("Content-Length", String.valueOf(httpEntity.getContentLength()));
content = httpEntity.getContent();
File tempFile = File.createTempFile("byteFile", null);
FileCopyUtils.copy(StreamUtils.copyToByteArray(content), tempFile);
fileInputStream = new FileInputStream(tempFile);
bos = new BufferedOutputStream(response.getOutputStream());
byte[] buff = new byte[2048];
int bytesRead;
while (-1 != (bytesRead = fileInputStream.read(buff, 0, buff.length))) {
bos.write(buff, 0, bytesRead);
}
} finally {
if (content != null) {
content.close();
}
if (fileInputStream != null) {
fileInputStream.close();
}
if (bos != null) {
bos.close();
}
}
}