用jAVA做的web工程中文档下载是怎么实现的

2025-02-24 13:52:41
推荐回答(1个)
回答1:

public static void downloadFile( String filePath, HttpServletResponse response) {

String fileName = ""; //文件名,输出到用户的下载对话框
//从文件完整路径中提取文件名,并进行编码转换,防止不能正确显示中文名
try {
if(filePath.lastIndexOf("/") > 0) {
fileName = new String(filePath.substring(filePath.lastIndexOf("/")+1, filePath.length()).getBytes("GB2312"), "ISO8859_1");
}else if(filePath.lastIndexOf("\\") > 0) {
fileName = new String(filePath.substring(filePath.lastIndexOf("\\")+1, filePath.length()).getBytes("GB2312"), "ISO8859_1");
}

}catch(Exception e) {}
//打开指定文件的流信息
FileInputStream fs = null;
try {
fs = new FileInputStream(new File(filePath));
}catch(FileNotFoundException e) {
e.printStackTrace();
return;
}
//设置响应头和保存文件名
response.reset();
response.setContentType("APPLICATION/OCTET-STREAM");
response.setHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\"");
//写出流信息
int b = 0;
try {
PrintWriter out = response.getWriter();
while((b=fs.read())!=-1) {
out.write(b);
}
fs.close();
out.close();
System.out.println("文件下载完毕.");
}catch(Exception e) {
e.printStackTrace();
System.out.println("下载文件失败!");
}
}

我随便找了个都能用,中文路径没有问题。 fileName = new String(filePath.substring(filePath.lastIndexOf("/")+1, filePath.length()).getBytes("GB2312"), "ISO8859_1"); 这个地方转码了。