package com.pb.down;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.io.IOUtils;
/**
* fileuploadDemo1
*
* DownServlet.java
* 创建人:TODO
* 时间:2016-9-22-下午8:42:35
*
*/
/**
*
* DownServlet
* 创建人:CAO
* 时间:2016-9-22
* @version 1.0.0
*
*/
public class DownServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
System.out.println("aaaaaa");
doPost(request, response);
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String filename = request.getParameter("path");
// GET请求中,参数中包含中文需要自己动手来转换。
// 当然如果你使用了“全局编码过滤器”,那么这里就不用处理了
filename = new String(filename.getBytes("ISO-8859-1"), "UTF-8");
String filepath = this.getServletContext().getRealPath("/WEB-INF/dwloads/" + filename);
File file = new File(filepath);
if(!file.exists()) {
response.getWriter().print("您要下载的文件不存在!");
return;
}
// 所有浏览器都会使用本地编码,即中文操作系统使用GBK
// 浏览器收到这个文件名后,会使用iso-8859-1来解码
filename = new String(filename.getBytes("GBK"), "ISO-8859-1");
response.addHeader("content-disposition", "attachment;filename=" + filename);
IOUtils.copy(new FileInputStream(file), response.getOutputStream());
}
}
jsp代码:
<c:set value="常见问题.doc" var="finame"></c:set>
<form action="DownServlet" method="post">
<input type="hidden" name ="path" value="${finame}"/>
<input type="submit" value="下载"/>
</form>