此处文件下载使用get请求,是因为扩展迅雷下载时发现迅雷下载的时候一直使用get请求进行下载。
文件下载
1.ResponseEntity方式文件下载
注:此方式基于SpringMVC
/**
* ResponseEntity<byte[]>方式文件下载
*/
@GetMapping("/responseEntityDownload")
public ResponseEntity<byte[]> downFile(){
File file = new File("E:\\文件上传测试", "mmexport1600165842010.jpg");
byte[] bytes = new byte[0];
try (
// 高效文件读取流
BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file));
) {
bytes = new byte[bis.available()];
bis.read(bytes);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
//将要下载文件内容返回
HttpHeaders httpHeaders = new HttpHeaders();
// httpHeaders.setContentType(MediaType.APPLICATION_OCTET_STREAM);
// httpHeaders.setContentDispositionFormData("attachment", URLEncoder.encode(file.getName(),"UTF-8"));
// 两种设置方式都可。
// httpHeaders.set("Content-Disposition","attachment;filename="+ file.getName() +"");
httpHeaders.set("Content-Disposition","attachment;filename="+ file.getName() +"");
ResponseEntity<byte[]> requestEntity = new ResponseEntity<byte[]>(bytes,httpHeaders, HttpStatus.OK);
return requestEntity;
}
2.response下载
/**
* responseDownload方式文件下载
*/
@GetMapping("/responseWhileDownload")
public void responseWhileDownload(HttpServletResponse response) throws IOException {
File file = new File("E:\\文件上传测试", "WPS_Setup_11830.exe");
byte[] bytes = null;
// response重置
response.reset();
// 设置编码
response.setCharacterEncoding("UTF-8");
// 设置流
response.setContentType("application/octet-stream");
// 设置header
response.addHeader("Content-Disposition","attachment;filename="+ URLEncoder.encode(file.getName(),"UTF-8") +"");
// 设置header告知大小
response.addHeader("Content-Length", "" + file.length());
ServletOutputStream outputStream = response.getOutputStream();
try (
// 高效文件读取流
BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file));
// response输出流
BufferedOutputStream bos = new BufferedOutputStream(outputStream)
) {
bytes = new byte[8192];
int length = 0;
// 读取完毕后会返回-1,故结束循环
while ((length = bis.read(bytes)) != -1){
bos.write(bytes, 0, length);
}
bis.close();
// 输出流切记要关闭不然无法完成下载
bos.close();
// response的输出流也必须关闭不然后台全是报错
outputStream.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
前端代码
<b>ResponseEntity方式文件下载</b><br>
<form action="<%=request.getContextPath()%>/file/responseEntityDownload" method="get" enctype="multipart/form-data" accept-charset="UTF-8">
<input type="submit" name="下载">
</form>
<b>response方式文件下载</b><br>
<form action="<%=request.getContextPath()%>/file/responseWhileDownload" method="get" enctype="multipart/form-data" accept-charset="UTF-8">
<input type="submit" name="下载">
</form>