文件下载功能是web开发中经常使用到的功能,使用HttpServletResponse对象就可以实现文件的下载
文件下载功能的实现思路:
1.获取要下载的文件的绝对路径
2.获取要下载的文件名
3.设置content-disposition响应头控制浏览器以下载的形式打开文件
4.获取要下载的文件输入流
5.创建数据缓冲区
6.通过response对象获取OutputStream流
7.将FileInputStream流写入到buffer缓冲区
8.使用OutputStream将缓冲区的数据输出到客户端浏览器
示例:通过Response实现文件下载(以ssm框架controller里接口类为例)
/**下载文件接口 通过OutputStream流
* @param request
* @param response
* @return
*/
@RequestMapping("/product/equipmentVersionQuery/dowloadFile.do")
public void dowloadFile(HttpServletRequest request,HttpServletResponse response){
String languageType = request.getParameter("language");
if(null != languageType && !"".equals(languageType)){
if(languageType.equals("en")){
languageType = "EN";
} else{
languageType = "CN";
}
} else{
languageType = "CN";
}
SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");
//获取要下载的文件名
try {
String excelName = AppFrameworkUtil.encodeExcelName(moduleName) + df.format(new Date());
if("EN".equals(languageType)){
excelName = AppFrameworkUtil.encodeExcelName(moduleNameEn) + df.format(new Date());
}
response.setContentType("application/vnd.ms-excel;charset=utf-8");
//设置content-disposition响应头控制浏览器以下载的形式打开文件
response.addHeader("Content-Disposition", "attachment;filename="+excelName+ ".png");
} catch (Exception e) {
e.printStackTrace();
}
//获取要下载的文件的绝对路径
String realPath = request.getSession().getServletContext().getRealPath("/images/module/curve_w.png");
InputStream in = null;
OutputStream out = null;
try {
//获取要下载的文件输入流
in = new FileInputStream(realPath);
int len = 0;
//创建数据缓冲区
byte[] buffer = new byte[1024];
//通过response对象获取outputStream流
out = response.getOutputStream();
//将FileInputStream流写入到buffer缓冲区
while((len = in.read(buffer)) > 0) {
//使用OutputStream将缓冲区的数据输出到浏览器
out.write(buffer,0,len);
}
out.flush();
in.close();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally{
if (out != null) {
try {
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
也可以下载到服务器指定位置 通过BufferedOutputStream
/**下载文件到服务器指定位置 通过BufferedOutputStream
* @param request
* @param response
* @return
*/
@RequestMapping("/product/equipmentVersionQuery/dowloadFile.do")
public void dowloadFile(HttpServletRequest request,HttpServletResponse response){
//获取要下载的文件绝对路径
String realPath = request.getSession().getServletContext().getRealPath("/images/module/curve_w.png");
InputStream in = null;
OutputStream out = null;
try {
File file = new File(request.getSession().getServletContext().getRealPath("/") + "/demoExcel/img.png");
if(!file.exists())
{
file.createNewFile();
}
//创建BufferedOutputStream流
out = new BufferedOutputStream(new FileOutputStream(file));
in = new FileInputStream(realPath);
int len = 0;
//创建数据缓冲区
byte[] buffer = new byte[1024];
//将FileInputStream流写入到buffer缓冲区
while((len = in.read(buffer)) > 0) {
//使用BufferedOutputStream将缓冲区的数据输出到指定位置文件
out.write(buffer,0,len);
}
out.flush();
in.close();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally{
if (out != null) {
try {
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
如果是导出excel到指定位置就简单的多,直接用创建好返回的workbook对象写入到输出流输出就好了
wb.write(out);
如:
//创建指定目录文件
File f = new File(request.getSession().getServletContext().getRealPath("/") + "/demoExcel/demo.xls");
if(!f.exists())
{
f.createNewFile();
}
BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(f));
wb.write(out);
//关闭流
out.flush();
out.close();
补充:
如果是下载到浏览器不知道是什么类型的文件的话,可以设置response表头:
/* 设置文件ContentType类型,这样设置,会自动判断下载文件类型 */
response.setContentType("multipart/form-data");
例如:
public void downloadFile(File file, HttpServletRequest request, HttpServletResponse response,String
nameString ,String suffixName) throws Exception {
boolean success = false;
InputStream fis = new FileInputStream(file);
/* 设置文件ContentType类型,这样设置,会自动判断下载文件类型 */
response.setContentType("multipart/form-data");
//response.setContentType("application/OCTET-STREAM;charset=UTF-8");
/* 设置文件头:最后一个参数是设置下载文件名 */
String formFileName = new String(nameString.getBytes("UTF-8"), "ISO-8859-1");
response.setHeader("Content-Disposition", "attachment;filename=" + formFileName + "." +suffixName);
try {
OutputStream os = response.getOutputStream();
byte[] b = new byte[1024 * 1024 * 200];
int len;
while ((len = fis.read(b)) > 0) {
os.write(b, 0, len);
}
os.flush();
os.close();
fis.close();
success=true;
} catch (Exception e) {
success = false;
e.printStackTrace();
}
}
网友评论