站内搜索: 请输入搜索关键词

当前页面: 开发资料首页JSP 专题jsp页面中的下载功能实现

jsp页面中的下载功能实现

摘要: jsp页面中的下载功能实现


<%@ page contentType="text/html; charset=gb2312" %>
<%@ page import="java.io.*"%>

<%!
public String toUtf8String(String s) {///源于网上
StringBuffer sb = new StringBuffer();
for (int i=0;i char c = s.charAt(i);
if (c >= 0 && c <= 255) {
sb.append(c);
} else {
byte[] b;
try {
b = Character.toString(c).getBytes("utf-8");
} catch (Exception ex) {
System.out.println(ex);
b = new byte[0];
}
for (int j = 0; j < b.length; j++) {
int k = b[j];
if (k < 0) k += 256;
sb.append("%" + Integer.toHexString(k).
toUpperCase());
}
}
}
return sb.toString();
}
%>
<%

String filename="test.jpg";
String dirName=application.getRealPath("/WEB-INF/upload");
java.io.File ff=null;
String dd=dirName+System.getProperties().getProperty("file.separator")+filename;
try{
ff=new java.io.File(dd);
}
catch(Exception e){
e.printStackTrace();
}
if (ff!=null&&ff.exists()&&ff.isFile())
{
long filelength = ff.length();
InputStream inStream=new FileInputStream(dd);
//设置输出的格式
response.reset();
response.setContentType("application/x-msdownload");
response.setContentLength((int)filelength);
response.addHeader("Content-Disposition","attachment; filename=\"" + toUtf8String(filename) + "\"");
//循环取出流中的数据
byte[] b = new byte[100];
int len;
while((len=inStream.read(b)) >0)
response.getOutputStream().write(b,0,len);
inStream.close();

}
%>



↑返回目录
前一篇: 怎么把查询参数传给分页的类
后一篇: 如何在Web页上实现文件上传