这是在JavaBlog看到的一个用户下载Servlet的源码。因为最近忙活的WebExplorer项目需要一个这样的功能,所以去下了一个,其实在公司我也遇到这样的功能,只不过因为不是我负责的,所以看过就忘了,重新需要了,没办法,只能通过Baidu来搜索。
其实JavaBlog是一个很强的Blog网站,因为网站平平无奇,但却可以在里面搜得很多很有用的文章,可见老牌就是不一样。
这段代码只有doGet,没有doPost方法,完全可以把doPost里面写入doGet(request,response);
public class DownloadServlet extends HttpServlet {
private String contentType = "application/x-msdownload";
private String enc = "utf-8";
private String fileRoot = "";
/**
* 初始化contentType,enc,fileRoot
*/
public void init(ServletConfig config) throws ServletException {
String tempStr = config.getInitParameter("contentType");
if (tempStr != null && !tempStr.equals("")) {
contentType = tempStr;
}
tempStr = config.getInitParameter("enc");
if (tempStr != null && !tempStr.equals("")) {
enc = tempStr;
}
tempStr = config.getInitParameter("fileRoot");
if (tempStr != null && !tempStr.equals("")) {
fileRoot = tempStr;
}
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String filepath = request.getParameter("filepath");
String fullFilePath = fileRoot + filepath;
/*读取文件*/
File file = new File(fullFilePath);
/*如果文件存在*/
if (file.exists()) {
String filename = URLEncoder.encode(file.getName(), enc);
response.reset();
response.setContentType(contentType);
response.addHeader("Content-Disposition", "attachment; filename=\"" + filename + "\"");
int fileLength = (int) file.length();
response.setContentLength(fileLength);
/*如果文件长度大于0*/
if (fileLength != 0) {
/*创建输入流*/
InputStream inStream = new FileInputStream(file);
byte[] buf = new byte[4096];
/*创建输出流*/
ServletOutputStream servletOS = response.getOutputStream();
int readLength;
while (((readLength = inStream.read(buf)) != -1)) {
servletOS.write(buf, 0, readLength);
}
inStream.close();
servletOS.flush();
servletOS.close();
}
}
}