package com.cn; import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.URLEncoder; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * Servlet implementation class Download */ @WebServlet("/Download") public class Download extends HttpServlet { private static final long serialVersionUID = 1L; /** * @see HttpServlet#HttpServlet() */ public Download() { super(); // TODO Auto-generated constructor stub } /** * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse * response) */ protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String name = "aaa.*";// 文件名 String uploadPath = UploadFileHelper.getRepositoryPath() + "//";// 文件来源 String filePath = name; String fileName = name; //处理文件名包含中文,浏览器乱码 if (request.getHeader("User-Agent").toLowerCase().indexOf("firefox") > 0) { fileName = new String(fileName.getBytes("UTF-8"), "ISO8859-1");// firefox浏览器 } else { if (request.getHeader("User-Agent").toUpperCase().indexOf("MSIE") > 0) { fileName = URLEncoder.encode(fileName, "UTF-8");// IE浏览器 } } response.setContentType("text/plain"); response.setHeader("Location", fileName); response.reset(); response.setHeader("Cache-Control", "max-age=0"); response.setHeader("Content-Disposition", "attachment; filename=" + fileName); BufferedInputStream bis = null; BufferedOutputStream bos = null; OutputStream fos = null; InputStream fis = null; filePath = uploadPath + filePath; fis = new FileInputStream(filePath); bis = new BufferedInputStream(fis); fos = response.getOutputStream(); bos = new BufferedOutputStream(fos); int bytesRead = 0; byte[] buffer = new byte[5 * 1024]; while ((bytesRead = bis.read(buffer)) != -1) { bos.write(buffer, 0, bytesRead);// 将文件发送到客户端 } bos.close(); bis.close(); fos.close(); fis.close(); } /** * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse * response) */ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } }
时间: 2024-10-27 08:52:34