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

java实现文件下载功能,自动弹出保存窗口

2014-08-30 10:37 931 查看
public void download() {
String filePath = this.queueService.getCsvFilePathById(id);
try {
File file = new File(filePath);
String fileName = filePath.substring(filePath.lastIndexOf(File.separator)+1);
fileName = new String(fileName.getBytes("UTF-8"),"ISO8859-1");
response.setContentType("application/octet-stream");
response.addHeader("Content-Disposition", "attachment;filename="+fileName);
String len = String.valueOf(file.length());
response.setHeader("Content-Length", len);
OutputStream out = response.getOutputStream();
FileInputStream in = new FileInputStream(file);
byte[] b = new byte[1024];
int n;
while((n=in.read(b))!=-1){
out.write(b, 0, n);
}
in.close();
out.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}

以上是代码,下面是同样的代码,只是多了一些注释:

public void download() {
String filePath = this.queueService.getCsvFilePathById(id);//所要下载的文件路径,从数据库中查询得到,当然也可以直接写文件路径,如:C:\\Users\\Administrator\\Desktop\\csv\\号码_utf8_100.csv
try {
File file = new File(filePath);
String fileName = filePath.substring(filePath.lastIndexOf(File.separator)+1);//得到文件名
fileName = new String(fileName.getBytes("UTF-8"),"ISO8859-1");//把文件名按UTF-8取出并按ISO8859-1编码,保证弹出窗口中的文件名中文不乱码,中文不要太多,最多支持17个中文,因为header有150个字节限制。
response.setContentType("application/octet-stream");//告诉浏览器输出内容为流
response.addHeader("Content-Disposition", "attachment;filename="+fileName);//Content-Disposition中指定的类型是文件的扩展名,并且弹出的下载对话框中的文件类型图片是按照文件的扩展名显示的,点保存后,文件以filename的值命名,保存类型以Content中设置的为准。注意:在设置Content-Disposition头字段之前,一定要设置Content-Type头字段。
String len = String.valueOf(file.length());
response.setHeader("Content-Length", len);//设置内容长度
OutputStream out = response.getOutputStream();
FileInputStream in = new FileInputStream(file);
byte[] b = new byte[1024];
int n;
while((n=in.read(b))!=-1){
out.write(b, 0, n);
}
in.close();
out.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐