jsp页面有个“模板下载”按钮,点击按钮后,将位于服务器端的某个文件夹下的excel模板文件打开,只用打开就可以,请求帮助怎么实现?
对,我的示例代码大致上是这样的,你按需修改
[code="java"]
protected void downloadFile(String filePath, String showNam, boolean isOnLine) throws IOException{
File f = new File(filePath);
HttpServletResponse response = getResponse();
if (!f.exists()) {
response.sendError(404, "File not found!");
return ;
}
response.reset(); //非常重要
if (isOnLine) { //在线打开方式
URL u = new URL("file:///" + filePath);
response.setContentType(u.openConnection().getContentType());
response.setHeader("Content-Disposition", "inline; filename=\"" + new String(showNam.getBytes("gb2312"),"iso-8859-1") + "\"");
//文件名应该编码成UTF-8
}
else { //纯下载方式
response.setContentType("application/x-msdownload");
response.setHeader("Content-Disposition", "attachment; filename=\""+ new String(showNam.getBytes("gb2312"),"iso-8859-1") + "\"");
}
InputStream inStream = new FileInputStream(f);
OutputStream outStream = response.getOutputStream();
byte[] b = new byte[100];
int len;
try {
while ((len = inStream.read(b)) > 0) outStream.write(b, 0, len);
inStream.close();
} catch (IOException e) {
logger.error("file [" + f + "] download fail.");
logger.error(e);
}
outStream.flush();
outStream.close();
}
[/code]
加上
[code="java"]URL u = new URL("file:///" + filePath);
response.setContentType(u.openConnection().getContentType());
response.setHeader("Content-Disposition", "inline; filename=\"" + new String(showNam.getBytes("gb2312"),"iso-8859-1") + "\"");[/code]
就可以了
[quote]showNam 是什么类呢[/quote]
文件名字
:oops: 你都写死都可以
你按需要来变动吧
showNam 不是类,应该是showName的意思,要显示的文件名。