下载文件代码
麻烦看下下面这段代码为什么不能实现下载文件的功能?
if(null != file){
byte [] buffer = new byte [1024]; // 缓冲区
OutputStream output = null ;
InputStream input = null ;
try{
response.setContentType("application/text/plain");
response.setHeader("Content-Disposition", "attachment; filename="+checkFileFileName);
output = response.getOutputStream();
input = new BufferedInputStream(new FileInputStream(file));
int i = -1;
while ((i = input.read(buffer)) != -1) {
output.write(buffer, 0, i);
}
output.flush();
} catch(Exception e) {
e.printStackTrace();
}
finally {
try{
if(input != null ) input.close();
if(output != null ) output.close();
} catch(IOException ioe) {
ioe.printStackTrace();
}
}
}
点击链接后进入这个方法正常执行完毕之后没有反应··
[解决办法]
是不是浏览器安全级别的问题.限制了文件下载?
[解决办法]
String fileName = "邮件信息导出.xml";
// 清空response
response.reset();
response.setContentType("text/xml;charset=utf-8");
// 设置response的Header
response.addHeader("Content-Disposition", "attachment;filename="
+ new String(fileName.getBytes("gbk"), "iso-8859-1")); // 转码之后下载的文件不会出现中文乱码
StringBuffer sb = new StringBuffer();
sb.append("<?xml version="1.0" encoding="UTF-8"?>\n");
sb.append("<items>\n");
for (int i = 0; i < 10; i++) {
sb.append("<item>"+i+"</item>\n");
}
sb.append("</items>");
response.addHeader("Content-Length", ""
+ sb.toString().getBytes().length);
try {
OutputStream toClient = new BufferedOutputStream(
response.getOutputStream());
toClient.write(sb.toString().getBytes());
toClient.flush();
toClient.close();
} catch (Exception e) {
e.printStackTrace();
}