Servlet实现文件下载以及遇到的问题

Servlet实现文件下载以及文件乱码问题


1.实现是sevlet类
import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class DownLoadQueryStatLineChartDataAction extends HttpServlet {

	protected void service(HttpServletRequest req, HttpServletResponse resp)  
            throws ServletException, IOException {
		req.setCharacterEncoding("utf-8");
		resp.setCharacterEncoding("utf-8");
		
		resp.setHeader("content-disposition", "attachment;filename=data.txt");
		PrintWriter out =  resp.getWriter();
		out.println("Test!");
		
		out.flush();
	    out.close();
	}
}

2.接着是 web.xml
<servlet>
  	<servlet-name>downLoadQueryStatLineChartDataAction</servlet-name>
  	<servlet-class>DownLoadQueryStatLineChartDataAction</servlet-class>
  </servlet> 
  
  <servlet-mapping>
  	<servlet-name>downLoadQueryStatLineChartDataAction</servlet-name>
  	<url-pattern>/downLoadQueryStatLineChartDataAction</url-pattern>
  </servlet-mapping>

3.然后我们尝试在页面调用:
<a href="downLoadQueryStatLineChartDataAction">下载</a>

这时候点击就能下载该文件了。

在实际项目中我遇到了一些中文乱码问题:
1.在Tomcat的conf目录下server.xml中Connector节点添加 URIEncoding="UTF-8"属性
2. 在Servlet中修改
resp.setContentType("application/octet-stream;charset=gb2312"); 
resp.setHeader("content-disposition", "attachment;filename=test.csv");

BufferedOutputStream write = new BufferedOutputStream(resp.getOutputStream());  
write.write(text.toString().getBytes("gb2312"));//这里test就是我要输出的文件内容。

这里不能使用utf-8,因为我使用的是csv文件,否则会有中文乱码!


©️2020 CSDN 皮肤主题: 大白 设计师:CSDN官方博客 返回首页