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();
}
}
} }

最新文章

  1. web Api 返回json 的两种方式
  2. 1Z0-053 争议题目解析607
  3. centos安装lamp环境
  4. 快速排序-java
  5. Android成长日记-使用ViewFlipper实现屏幕切换动画效果
  6. PyCharm 教程(四)显示行号
  7. jQuery源代码阅读之二——jQuery静态属性和方法
  8. PDF 补丁丁 0.4.2.1023 测试版发布:新增旋转页面功能
  9. python基础语法(1)
  10. AppPoolService-IIS应用程序池辅助类(C#控制应用程序池操作)
  11. JAVA内存区域和GC机制
  12. 使用高德地图API
  13. 怎样从ext3升级到ext4?
  14. oracle 包,函数,过程,块的创建和执行及在java中执行(转)
  15. Android 安装镜像
  16. python装饰器练习题
  17. ML笔记_机器学习基石01
  18. Java开发笔记(四)Java帝国的度量衡
  19. 使用VS调试DUMP文件
  20. c++ protobuf序列化

热门文章

  1. vscode eslint配置vue遇到的问题
  2. poj3009 Curling 2.0(很好的题 DFS)
  3. __c语言__结构体、共用体、枚举__笔记
  4. ionic andorid apk 签名, 查看签名MD5
  5. docker 端口映射 及外部无法访问问题
  6. 【php】php输出jquery的轮询,5秒跳转指定url
  7. 关于Discuz! X系列UC_Server 本地文件包含漏洞
  8. iOS Xcode 10: Multiple commands produce
  9. TensorFlow+Keras 01 人工智能、机器学习、深度学习简介
  10. python3 + flask + sqlalchemy +orm(2):数据库中添加表