js:
downloadiframe.location.href='';
java:
response.setCharacterEncoding("gb2312");
String path = outfile.getAbsolutePath();
log.debug(path);
response.reset();
response.setContentType("application/x-download");
int last1 = path.lastIndexOf("\\");
int last2 = path.lastIndexOf("/");
String filedisplay = path.substring((last1 > last2 ? last1 : last2) + 1);
filedisplay = URLEncoder.encode(filedisplay, "UTF-8");
response.addHeader("Content-Disposition", "attachment;filename="
+ filedisplay);
OutputStream outp = null;
FileInputStream in = null;
File fp = new File(path);
try {
outp = response.getOutputStream();
in = new FileInputStream(fp);
byte[] b = new byte[1024];
int i = 0;
while ((i = in.read(b)) > 0) {
outp.write(b, 0, i);
}
outp.flush();
} finally {
in.close();
outp.close();
}
downloadiframe.location.href='';
java:
response.setCharacterEncoding("gb2312");
String path = outfile.getAbsolutePath();
log.debug(path);
response.reset();
response.setContentType("application/x-download");
int last1 = path.lastIndexOf("\\");
int last2 = path.lastIndexOf("/");
String filedisplay = path.substring((last1 > last2 ? last1 : last2) + 1);
filedisplay = URLEncoder.encode(filedisplay, "UTF-8");
response.addHeader("Content-Disposition", "attachment;filename="
+ filedisplay);
OutputStream outp = null;
FileInputStream in = null;
File fp = new File(path);
try {
outp = response.getOutputStream();
in = new FileInputStream(fp);
byte[] b = new byte[1024];
int i = 0;
while ((i = in.read(b)) > 0) {
outp.write(b, 0, i);
}
outp.flush();
} finally {
in.close();
outp.close();
}
Java文件下载实现
本文介绍了一种使用Java实现文件下载的方法。通过设置HTTP响应头来指定文件编码和内容类型,并利用FileInputStream读取文件,再通过Servlet输出流将文件内容写入到客户端,实现了文件的下载功能。

被折叠的 条评论
为什么被折叠?



