public class DownloadServlet extends HttpServlet {
private String contentType = "application/x-msdownload";//也可以是文件的mime
private String enc = "utf-8";
private String fileRoot = "d:/";
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();
}
}
}
http://www.blogjava.net/mstar/archive/2005/10/27/17113.html
response.setContentType 对应的文件类型
image/bmp--BMP
image/gif--GIF
image/jpeg--JPEG
image/tiff--TIFF
image/x-dcx--DCX
image/x-pcx--PCX
text/html--HTML
text/plain--TXT
text/xml--XML
application/afp--AFP
application/pdf--PDF
application/rtf--RTF
application/msword--MSWORD
application/vnd.ms-excel--MSEXCEL
application/vnd.ms-powerpoint--MSPOWERPOINT
application/wordperfect5.1--WORDPERFECT
application/vnd.lotus-wordpro--WORDPRO
application/vnd.visio--VISIO
application/vnd.framemaker--FRAMEMAKER
application/vnd.lotus-1-2-3--LOTUS123