首页 > 代码库 > 文件下载
文件下载
最重要的两点是设置响应头
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); } }
文件下载
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。