文件下载
Posted Wayfo
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了文件下载相关的知识,希望对你有一定的参考价值。
public class HelloServlet extends HttpServlet { @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //设置浏览器响应的mime类型 response.setContentType("application/msword"); //从服务器中获取要下载的文件的路径 String realPath = getServletContext().getRealPath("/error/myword.docx"); File file = new File(realPath); try { //获取该文件的输入流 FileInputStream inputStream = new FileInputStream(file); //通过response获取ServletOutputStream对象(out) ServletOutputStream outputStream = response.getOutputStream(); //通过字节流的方式将文件写会浏览器 int b = 0; byte[] buffer = new byte[1024]; while (b != -1){ b = inputStream.read(buffer); //写到输出流(out)中 outputStream.write(buffer,0,b); } inputStream.close(); outputStream.close(); outputStream.flush(); } catch (IOException e) { e.printStackTrace(); } } }
以上是关于文件下载的主要内容,如果未能解决你的问题,请参考以下文章
在Tomcat的安装目录下conf目录下的server.xml文件中增加一个xml代码片段,该代码片段中每个属性的含义与用途