您的位置:首页 > 编程语言 > Java开发

java 下载文件 例:excel

2013-05-10 17:32 405 查看
button提交

String filepath = request.getSession().getServletContext().getRealPath("");

String fileName;

fileName = "expenditure.xls";

File file= new File(filepath + "/" + fileName);

try {

//输出流用来向response输出数据

BufferedOutputStream output = new BufferedOutputStream(response.getOutputStream());

// 输入流用来从文件读入数据

BufferedInputStream input = new BufferedInputStream(new FileInputStream(file));

String filename = file.getName();

long fileLength = file.length();

int iFileContent = 0;

byte buffer[] = new byte[2048];

response.reset();

response.setContentType("application/ms-excel"); //文件的保存类型为MS-excel类型

response.setHeader("Content-Disposition", "attachment;filename=\""+URLEncoder.encode(filename, "UTF-8")+"\"");

//URLEncoder.encode(filename, "UTF-8")可以解决中文名乱码问题

response.setContentLength((int)fileLength); //设置文件长度

while((iFileContent = input.read(buffer, 0, 2048)) !=-1){

response.getOutputStream().write(buffer, 0, iFileContent);

}

response.flushBuffer();

input.close();

output.close();

} catch (IOException e1) {

e1.printStackTrace();

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: