Survive by day and develop by night.
talk for import biz , show your perfect code,full busy,skip hardness,make a better result,wait for change,challenge Survive.
happy for hardess to solve denpendies.
目录
概述
文件下载的是一个非常常见的需求。
需求:
设计思路
实现思路分析
1.下载的方法
public void down1(String path,HttpServletResponse response,String contentType) throws Exception {
// response.reset();
response.setContentType("application/octet-stream;charset=utf-8");
File file = new File(path);
String filename = file.getName();
response.addHeader("Content-Disposition", "attachment;filename=" + new String(filename.getBytes()));
try(
BufferedInputStream bis = new BufferedInputStream(new FileInputStream(new File(path)));
// 输出流
BufferedOutputStream bos = new BufferedOutputStream(response.getOutputStream());
){
// response.setContentType(contentType);
byte[] buff = new byte[1024];
int len = 0;
while ((len = bis.read(buff)) > 0) {
bos.write(buff, 0, len);
}
}
}
public String downloadFile(String path,
HttpServletResponse response) throws UnsupportedEncodingException {
// 获取指定目录下的第一个文件
// 如果文件名不为空,则进行下载
if (path != null) {
//设置文件路径
File file = new File(path);
String filename = file.getName();
// 如果文件名存在,则进行下载
if (file.exists()) {
// 配置文件下载
response.setHeader("content-type", "application/octet-stream");
response.setContentType("application/octet-stream");
// 下载文件能正常显示中文
response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(filename, "UTF-8"));
// 实现文件下载
byte[] buffer = new byte[1024];
FileInputStream fis = null;
BufferedInputStream bis = null;
try {
fis = new FileInputStream(file);
bis = new BufferedInputStream(fis);
OutputStream os = response.getOutputStream();
int i = bis.read(buffer);
while (i != -1) {
os.write(buffer, 0, i);
i = bis.read(buffer);
}
System.out.println("Download the song successfully!");
}
catch (Exception e) {
System.out.println("Download the song failed!");
}
finally {
if (bis != null) {
try {
bis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (fis != null) {
try {
fis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
return null;
}
public ResponseEntity<InputStreamResource> down2(String path) throws Exception {
InputStreamResource isr = new InputStreamResource(new FileInputStream(new File(path)));
return ResponseEntity.ok()
.contentType(MediaType.APPLICATION_OCTET_STREAM)
.header("Content-disposition", "attachment; filename=test1.png")
.body(isr);
}
public ResponseEntity<ByteArrayResource> down3(String path) throws Exception {
byte[] bytes = Files.readAllBytes(new File(path).toPath());
ByteArrayResource bar = new ByteArrayResource(bytes);
return ResponseEntity.ok()
.contentType(MediaType.APPLICATION_OCTET_STREAM)
.header("Content-disposition", "attachment; filename=test2.png")
.body(bar);
}
参考资料和推荐阅读
[1]. https://blog.csdn.net/weixin_43296313/article/details/125100824
欢迎阅读,各位老铁,如果对你有帮助,点个赞加个关注呗!~