2010年(59)
分类: 系统运维
2010-04-14 22:51:52
HTTP协议文件下载
Servlet如下:
import java.io.BufferedInputStream;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.ServletOutputStream;
public class FileDownloadServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
response.setHeader("Cache-Control","no-cache");
request.setCharacterEncoding("gbk");
String realName = (String)request.getParameter("realName");
String path = (String)request.getParameter("path");
String type = (String)request.getParameter("type");
String httpurl = "";
realName = java.net.URLEncoder.encode(realName,"utf-8");
response.addHeader("Content-Disposition", "attachment;filename="+ realName);
URL url = new java.net.URL(httpurl);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.connect();
BufferedInputStream bis = new BufferedInputStream(connection.
getInputStream());
int read = bis.read();
ServletOutputStream sos = response.getOutputStream();
while (read != -1) {
sos.write(read);
read = bis.read();
}
bis.close();
sos.close();
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request,response);
}
}