<%@ page import="java.io.*"%>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<%
response.setCharacterEncoding("UTF-8");
request.setCharacterEncoding("UTF-8");
String filepath = new String(request.getAttribute("redirectUrl")
.toString().getBytes("ISO-8859-1"), "UTF-8");
System.out.println("============================" + filepath);
if (filepath != null) {
OutputStream os = null;
FileInputStream fis = null;
try {
String file = filepath;
if (!(new File(file)).exists()) {
System.out.println("没有文件");
return;
}
String filename = file
.substring(file.lastIndexOf("\\") + 1);
System.out.println("文件名为:" + filename);
os = response.getOutputStream();
response.setHeader("content-disposition",
"attachment;filename="
+ new String(filename.getBytes("GBK"),
"ISO-8859-1"));
response.setContentType("application/octet-stream");//八进制流 与文件类型无关
byte temp[] = new byte[1024];
fis = new FileInputStream(file);
int n = 0;
while ((n = fis.read(temp)) != -1) {
os.write(temp, 0, n);
}
} catch (Exception e) {
out.print("出错了");
} finally {
if (os != null)
os.close();
if (fis != null)
fis.close();
}
out.clear();
out = pageContext.pushBody();
}
%>
用来下载服务器上的文件,支持中文文件名,路径
来源于百度来的某个文章
稍许更改
本文介绍了一个使用Java实现的服务器端文件下载功能,支持中文文件名和路径。通过设置HTTP响应头来实现文件的正确下载,并确保了文件内容的正确传输。
1278

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



