然后
default
org.apache.catalina.servlets.DefaultServlet
debug
0
listings
false
1
要将listings的false改为true。
这样直接在图上点击文件名,或者对着浏览器输入文件的地址就能看到文件内容。连接另存为就能下载。如果文件名包含中文,就在
{tomcat_home}/conf/server.xml中加上URIEncoding="UTF-8,如下:
上面的效果其实还不错,但是也有问题
。
之后我访问
但是还有一个问题,不能下载。
我不想在浏览器里看到txt文档,我想直接下载txt,可以么?
可以。
其实还有几个问题在方案一里面,最重要的参数是xml的文件名,即使给context里面加上path也不顶用
在方案二里面,server.xml里面起作用的却是contxt里面的psth 有点奇怪哦
/**
* This class is used for ...
* @author dlf([email protected])
* @version 1.0, 2017年4月8日 下午11:53:35
*/
@WebServlet(urlPatterns="/module/book/downtest")
public class DownloadFile extends HttpServlet{
/**
*
*/
private static final long serialVersionUID = -8663217572193783988L;
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
//获得请求文件名
String filenameISO = (String) request.getParameter("filename");
String filenameUTF= new String(filenameISO.getBytes("ISO-8859-1"), "UTF-8");
System.out.println(filenameUTF);
//设置文件MIME类型
response.setContentType(getServletContext().getMimeType(filenameUTF));
//设置Content-Disposition
//filename是ISO-8859-1的 如果改成utf-8 下载的文件名中就不能出现中文了
//大家可以试试
response.setHeader("Content-Disposition", "attachment;filename="+filenameISO);
response.setHeader("Content-type", "charset=UTF-8");
response.setCharacterEncoding("UTF-8");
//读取目标文件,通过response将目标文件写到客户端
//System.out.println(fullFileName);
//读取文件
InputStream in = new FileInputStream(Config.FAILED_FILE_PATH+filenameUTF);
OutputStream out = response.getOutputStream();
//写文件
int b;
while((b=in.read())!= -1) {
out.write(b);
}
in.close();
out.close();
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}
}