在Servlet中写入以下代码:
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// 下载文件到本地
String filePath = "c:/cdkyes.txt"; //被下载的文件的路径
String fileName = "cdkyes.txt"; //下载后文件的默认文件名,显示在点击下载后弹出的保存对话框
fileName = URLEncoder.encode(fileName, "utf-8");
// 清除输出缓冲区中的数据
response.reset();
response.setContentType("application/x-download" + ";charset=UTF-8"); //设置输出格式,application/x-msdownload则是将下面文件内容显示在页面上
response.setHeader("content-disposition", "attachment;filename="
+ fileName);
BufferedInputStream bis = null;
BufferedOutputStream bos = null;
try {
bis = new BufferedInputStream(new FileInputStream(filePath));
bos = new BufferedOutputStream(response.getOutputStream());
byte[] buff = new byte[2048];
int bytesRead;
while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) {
bos.write(buff, 0, bytesRead);
}
bos.flush();
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
System.err.println("出现未知错误 ");
} finally {
try {
if (bis != null)
bis.close();
if (bos != null)
bos.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}