HttpServletResponse实现文件下载
2024-10-18 19:26:11
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URLEncoder;
import javax.servlet.http.HttpServletResponse;
import org.springframework.util.StringUtils; /**
* 文件下载
*/
public class FileLoad { /**
* 使用response返回文件流
*/
public void loadFile(String filePath, HttpServletResponse response) {
// 声明工具类
BufferedInputStream in = null;
BufferedOutputStream out = null; try {
// 若路径为空
if (StringUtils.isEmpty(filePath)) {
throw new Exception("invalid filepath of null.");
} // 没找到文件
File file = new File(filePath);
if (!file.exists()) {
throw new Exception("file not exist in path [" + filePath + "]");
} // 获取文件名
String fileName = file.getName(); // 输出文件流到浏览器
in = new BufferedInputStream(new FileInputStream(filePath));
out = new BufferedOutputStream(response.getOutputStream());
response.setContentType("application/x-download;charset=utf-8");
response.setHeader("Content-disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8")); byte[] buffer = new byte[8192];
int count = 0;
while ((count = in.read(buffer, 0, 8192)) != -1) {
out.write(buffer, 0, count);
} out.flush();
file = null;
} catch (Exception e) {
e.printStackTrace();
} finally {
closeStream(in, out);
}
} /**
* 关闭输入输出流
*/
public void closeStream(InputStream in, OutputStream out) {
if (null != in) {
try {
in.close();
} catch (IOException e) {
// e.printStackTrace();
}
}
if (null != out) {
try {
out.close();
} catch (IOException e) {
// e.printStackTrace();
}
}
} }
最新文章
- web Api 返回json 的两种方式
- 1Z0-053 争议题目解析607
- centos安装lamp环境
- 快速排序-java
- Android成长日记-使用ViewFlipper实现屏幕切换动画效果
- PyCharm 教程(四)显示行号
- jQuery源代码阅读之二——jQuery静态属性和方法
- PDF 补丁丁 0.4.2.1023 测试版发布:新增旋转页面功能
- python基础语法(1)
- AppPoolService-IIS应用程序池辅助类(C#控制应用程序池操作)
- JAVA内存区域和GC机制
- 使用高德地图API
- 怎样从ext3升级到ext4?
- oracle 包,函数,过程,块的创建和执行及在java中执行(转)
- Android 安装镜像
- python装饰器练习题
- ML笔记_机器学习基石01
- Java开发笔记(四)Java帝国的度量衡
- 使用VS调试DUMP文件
- c++ protobuf序列化
热门文章
- vscode eslint配置vue遇到的问题
- poj3009 Curling 2.0(很好的题 DFS)
- __c语言__结构体、共用体、枚举__笔记
- ionic andorid apk 签名, 查看签名MD5
- docker 端口映射 及外部无法访问问题
- 【php】php输出jquery的轮询,5秒跳转指定url
- 关于Discuz! X系列UC_Server 本地文件包含漏洞
- iOS Xcode 10: Multiple commands produce
- TensorFlow+Keras 01 人工智能、机器学习、深度学习简介
- python3 + flask + sqlalchemy +orm(2):数据库中添加表