文件下载的Servlet

发表于:2007-07-01来源:作者:点击数: 标签:
//文件下载的Servlet import java x.servlet.*; import javax.servlet.http.*; import java.io.*; import java.util.*; public class downloadfile extends HttpServlet { private static final String CONTENT_TYPE = text/html; charset=GBK; //Initialize
//文件下载的Servlet

import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
import java.util.*;

public class downloadfile extends HttpServlet {
private static final String CONTENT_TYPE = "text/html; charset=GBK";
//Initialize global variables
public void init() throws ServletException {
}
//Process the HTTP Post request
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType(CONTENT_TYPE);

String pathsavefile;//要下载的文件
String fileName;//保存窗口中显示的文件名
fileName=response.encodeURL(new String(fileName.getBytes(),"ISO8859_1"));//转码

try
{
response.reset();
response.setContentType("APPLICATION/OCTET-STREAM");
response.setHeader("Content-Disposition", "attachment; filename=\""+fileName+"\"");
ServletOutputStream out = response.getOutputStream();
InputStream inStream=new FileInputStream(pathsavefile);
//循环取出流中的数据
byte[] b = new byte[1024];
int len;
while((len=inStream.read(b)) >0)
out.write(b,0,len);
}
out.close();
inStream.close();
}
catch (Exception e)
{
System.out.println(e);
}

}
//Clean up resources
public void destroy() {
}
}

原文转自:http://www.ltesting.net