文件下载
Posted 发福大叔
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了文件下载相关的知识,希望对你有一定的参考价值。
最重要的两点是设置响应头
1、设置contextType 响应头:通知客户端这是个下载文件
response.setContentType("application/x-msdownload");
2、设置content=Disposition 响应头:通知浏览器不再由自己自行处理要下载的文件,而是由客户自己下载
response.setHeader("content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "utf-8"));
jsp页面
<%@ page language="java" import="java.util.*" pageEncoding="ISO-8859-1"%> <% String path = request.getContextPath(); String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/"; %> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <base href="<%=basePath%>"> <title>My JSP ‘index.jsp‘ starting page</title> </head> <body> <a href="downLoadServlet">Study download</a> </body> </html>
servlet
package com.future.demo; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.PrintWriter; import java.net.URLEncoder; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; public class DownLoadServlet extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //设置contextType 响应头:通知客户端这是个下载文件 response.setContentType("application/x-msdownload"); //获取要下载的文件名字 String fileName = "文件下载.txt"; //设置content=Disposition 响应头:通知浏览器不再由自己自行处理要下载的文件,而是由客户自己下载 response.setHeader("content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "utf-8")); OutputStream os = response.getOutputStream();//不需要主动关流,是要用户自动处理的 //要下载的文件 InputStream is = new FileInputStream("C:\\Users\\Administrator\\Desktop\\ms.txt"); int len = 0; byte[] buffer = new byte[1024]; while((len=is.read(buffer))!=-1){ os.write(buffer, 0, len); } is.close(); //os.close(); } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } }
以上是关于文件下载的主要内容,如果未能解决你的问题,请参考以下文章
在Tomcat的安装目录下conf目录下的server.xml文件中增加一个xml代码片段,该代码片段中每个属性的含义与用途