jsp编程实例-附件下载功能的实现
浏览器响应用户的下载请求:
public downloadfile(String filepath,String filename,String fileTrueName,HttpServletResponse response,java.io.Writer aOut)
{
String fix = “”;
BufferedInputStream bis=null;
BufferedOutputStream bos=null;
try
{
int findex=fileTrueName.indexOf(“.”);
if (findex>=0)
fix = fileTrueName.substring(findex);
else
fix = fileTrueName;
response.setContentType( “application/x-msdownload; charset=”+str.getChineseCharset() );
response.setHeader(“Content-disposition”,”attachment;filename=\””+fileTrueName+”\””);
bis = new BufferedInputStream(new FileInputStream(filepath + filename));
bos = new BufferedOutputStream(response.getOutputStream());
byte[] buff = new byte[2048];
int bytesRead;
while ( -1 != (bytesRead = (bis.read(buff, 0, buff.length)))) {
bos.write(buff, 0, bytesRead);
}
}
catch (IOException e)
{
TDebugOutMsg.outMsg(“用户异常关闭文件下载框”,TDebugOutMsg.C_iMsgType_System);
}finally{
if (bis!=null){
try{
bis.close();
}catch (IOException e){
}
}
if (bos!=null){
try{
bos.close();
}catch (IOException e){
}
}
}
}
此时,用户点击文件时,会弹出相应的对话框。
Web开发时,可能遇到遇到几种情况:
a 希望某类或者某已知MIME 类型的文件(比如:*.gif;*.txt;*.htm)能够在访问时弹出“文件下载”对话框。
b 希望客户端下载时以指定文件名显示。
c 希望某文件直接在浏览器上显示而不是弹出文件下载对话框。
对于上面的需求,使用Content-Disposition属性就可以解决。代码示例:
response.setHeader(“Content-disposition”, “attachment;filename=” + fileName)。
/*Content-disposition为属性名。
attachment表示以附件方式下载。如果要在页面中打开,则改为inline。
filename如果为中文,则会出现乱码。解决办法有两种:
1、使用fileName = new String(fileName.getBytes(), “ISO8859-1”)语句
2、使用fileName = HttpUtility.UrlEncode(filename, System.Text.Encoding.UTF8)语句
*/
声明: 除非转自他站(如有侵权,请联系处理)外,本文采用 BY-NC-SA 协议进行授权 | 嗅谱网
转载请注明:转自《jsp编程实例-附件下载功能的实现》
本文地址:http://www.xiupu.net/archives-206.html
关注公众号:
微信赞赏
支付宝赞赏