一般来说文件下载需要的步骤为:
(1)获得客户端请求的文件的名称
String fileName = req.getParameter("fileName");
(2)获得服务器端的真实的物理路径
File dir = new File(super.getServletContext().getRealPath("/temp"));
(3)创建目标文件的输入流对象
File targetFile = new File(dir, fileName);
(4) 执行下载
<1>设置返回内容的类型
resp.setContentType("application/msword");//Content-Type
<2>设置返回内容的长度
resp.setContentLength((int)targetFile.length());//Content-Length
<3>设置怎样处理文件,征求客户的意见
resp.setHeader("Content-Disposition","attachment;filename=test.doc");
<4>利用tomcat的FileUtils.copyFile方法进行文件的下载
FileUtils.copyFile(targetFile, resp.getOutputStream());
FileDownloadServlet.java
package com.xixi.servlet;
import java.io.File;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.io.FileUtils;
@WebServlet(urlPatterns="/downloadServlet")
public class FileDownoloadServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
//设置字符编码
req.setCharacterEncoding("utf-8");
//获得请求的fileName的名称
String fileName = req.getParameter("fileName");
if (fileName!=null && fileName.length() > 0) {
//获得服务器端的真实的物理路径
File dir = new File(super.getServletContext().getRealPath("/temp"));
File targetFile = new File(dir, fileName);
if (targetFile.exists()) {
//执行下载
//设置返回内容的类型
resp.setContentType("application/msword");//Content-Type
//设置返回内容的长度
resp.setContentLength((int)targetFile.length());//Content-Length
//设置怎样处理文件,征求客户的意见
resp.setHeader("Content-Disposition", "attachment;filename=test.doc");
//利用tomcat的FileUtils.copyFile方法进行文件的下载
FileUtils.copyFile(targetFile, resp.getOutputStream());
}
}
}
}