springmvc实现浏览器下载文件
2016-07-14 10:42
477 查看
import org.springframework.util.FileCopyUtils;
/**
* 下载Excel
* @param request
* @param response
* @throws IOException
*/
public static byte[] getBytes(String filePath){
byte[] buffer = null;
try {
File file = new File(filePath);
FileInputStream fis = new FileInputStream(file);
ByteArrayOutputStream bos = new ByteArrayOutputStream(1000);
byte[] b = new byte[1000];
int n;
while ((n = fis.read(b)) != -1) {
bos.write(b, 0, n);
}
fis.close();
bos.close();
buffer = bos.toByteArray();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return buffer;
}
@RequestMapping("download")
public void download(HttpServletRequest request,HttpServletResponse response) throws IOException {
String time = request.getParameter("time");
String path = BaseUtil.readValue("PAYMENTORDER_EXCEL_BAK")+ "/收费记录_"+time+".xlsx";// 生成Excel的文件地址
String fileNameStr = "收费记录_"+time+".xlsx";
String fileName = new String(fileNameStr.getBytes("UTF-8"),"iso-8859-1");// 为了解决中文名称乱码问题
response.setContentType("application/x-msdownload");
response.setCharacterEncoding("UTF-8");
response.setHeader("Content-disposition", "attachment; filename=\""+ fileName + "\"");
FileCopyUtils.copy(getBytes(path),response.getOutputStream());
}
/**
* 下载Excel
* @param request
* @param response
* @throws IOException
*/
public static byte[] getBytes(String filePath){
byte[] buffer = null;
try {
File file = new File(filePath);
FileInputStream fis = new FileInputStream(file);
ByteArrayOutputStream bos = new ByteArrayOutputStream(1000);
byte[] b = new byte[1000];
int n;
while ((n = fis.read(b)) != -1) {
bos.write(b, 0, n);
}
fis.close();
bos.close();
buffer = bos.toByteArray();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return buffer;
}
@RequestMapping("download")
public void download(HttpServletRequest request,HttpServletResponse response) throws IOException {
String time = request.getParameter("time");
String path = BaseUtil.readValue("PAYMENTORDER_EXCEL_BAK")+ "/收费记录_"+time+".xlsx";// 生成Excel的文件地址
String fileNameStr = "收费记录_"+time+".xlsx";
String fileName = new String(fileNameStr.getBytes("UTF-8"),"iso-8859-1");// 为了解决中文名称乱码问题
response.setContentType("application/x-msdownload");
response.setCharacterEncoding("UTF-8");
response.setHeader("Content-disposition", "attachment; filename=\""+ fileName + "\"");
FileCopyUtils.copy(getBytes(path),response.getOutputStream());
}
相关文章推荐
- java读取Excel 格式.xls文件
- 反射学习笔记
- java递归和反向递归
- java反射详解
- window下eclipse中运行hbase
- javaweb同页面多验证码第一次验证错误的问题记录
- Java RuntimeException异常处理汇总
- java、jsp中相对路径与绝对路径问题
- Spring的注入案例分析(设值注入和构造注入)
- Java实现几种常见排序方法
- java 遍历map 方法 集合 五种的方法
- Synchronized在java中的用法
- java常用知识
- Java没有头文件的原因
- java 静态(static)方法与非静态方法
- Eclipse 安装反编译插件jadclipse
- 【奔跑的菜鸟】Java中的引用传递
- Java格式化UTC格式时间
- 使用eclipse调试openfre3.9.3源码
- Java后台模拟向Servlet发送POST文件上传请求(转载)