昨天做了一个Servlet,实现文档下载功能。
文档路径:C:\test\temp.doc
package Servlet;
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class Download extends HttpServlet{
private static int DEFAULT_BUFFER_SIZE=1024*4;
public void doGet(HttpServletRequest request,HttpServletResponse response)throws ServletException,IOException{
response.setContentType("text/html");
response.setCharacterEncoding("GB2312");
PrintWriter out=response.getWriter();
out.println("<HTML>");
out.println("<HEAD>");
out.println("<TITLE>");
out.println("下载");
out.println("</TITLE>");
out.println("</HEAD>");
out.println("<BODY>");
out.println("<form method=\"post\" action=\"download?file=c:\\test\\temp.doc\">");
out.println("<h2>请单击下载按钮下载文件</h2>");
out.println("<input type=\"submit\" value=\"下载\">");
out.println("</form>");
out.println("</BODY>");
out.println("</HTML>");
out.close();
}
public void doPost(HttpServletRequest request,HttpServletResponse response)throws ServletException,IOException{
String fileName=(String)request.getParameter("file");
ServletOutputStream output=null;
FileInputStream input=null;
File file=new File(fileName);
if(!file.exists())
throw new IOException("文件不存在");
try{
response.setHeader("Content-disposition", "attachment;filename=temp.doc");
response.setContentType("application/msword");
response.setContentLength((int)file.length());
output=response.getOutputStream();
input=new FileInputStream(file);
copy(input,output);
}catch(IOException e){e.printStackTrace();}
finally{if (output!=null)
output.close();
if(input!=null)
input.close();
}
}
private static int copy(InputStream input,OutputStream output)throws IOException{
byte[] buffer=new byte[DEFAULT_BUFFER_SIZE];
int count=0;
int n=0;
while(-1!=(n=input.read(buffer))){
output.write(buffer, 0, n);
count+=n;
}
return count;
}
}
Servlet配置信息如下:
<servlet>
<servlet-name>Download</servlet-name>
<display-name>download</display-name>
<description>A Download Servlet</description>
<servlet-class>Servlet.Download</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>Download</servlet-name>
<url-pattern>/download</url-pattern>
</servlet-mapping>
需要注意的问题。
1.配置路径为/download,不能是/Download.
2.response的几个方法的解读。
response.setHeader("Content-disposition", "attachment;filename=temp.doc");
//设置响应头信息,让下载的文件显示保存信息
response.setContentType("application/msword");
//设置下载文档的类型,
"application/msword"就是指word文档。还有
"application/pdf " :pdf文档
"application/zip": zip文档
…………
response.setContentLength((int)file.length());
//设置输出文件长度
response.getOutputStream();
//取得输出流,用于向客户发送二进制数据