使用原生态Servlet作文件下载

    技术2024-11-05  12

    @WebServlet("/DownloadServlet") public class DownloadServlet extends HttpServlet { protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //设置请求编码 request.setCharacterEncoding(“utf-8”); //获取需要下载的文件名 String fileName = request.getParameter(“fileName”) ; System.out.println(fileName); //设置两个 响应头 response.addHeader(“content-Type”, “application/octet-stream”); //获取客户端的User-Agent (判断用户用的什么浏览器) String browser = request.getHeader(“User-Agent”); if (-1 < browser.indexOf(“MSIE 6.0”) || -1 < browser.indexOf(“MSIE 7.0”)) { // IE6, IE7 浏览器 response.addHeader(“content-disposition”, “attachment;filename=” + new String(fileName.getBytes(), “ISO8859-1”)); } else if (-1 < browser.indexOf(“MSIE 8.0”)) { // IE8 response.addHeader(“content-disposition”, “attachment;filename=” + URLEncoder.encode(fileName, “UTF-8”)); } else if (-1 < browser.indexOf(“MSIE 9.0”)) { // IE9 response.addHeader(“content-disposition”, “attachment;filename=” + URLEncoder.encode(fileName, “UTF-8”)); } else if (-1 < browser.indexOf(“Chrome”)) { // 谷歌 response.addHeader(“content-disposition”, “attachment;filename*=UTF-8’’” + URLEncoder.encode(fileName, “UTF-8”)); } else if (-1 < browser.indexOf(“Safari”)) { // 苹果 response.addHeader(“content-disposition”, “attachment;filename=” + new String(fileName.getBytes(), “ISO8859-1”)); } else { // 火狐或者其他的浏览器 response.addHeader(“content-disposition”, “attachment;filename*=UTF-8’’” + URLEncoder.encode(fileName, “UTF-8”)); } // response.addHeader(“content-Disposition”, “attachment;filename=”+fileName); //Servlet通过文件的地址将文件转为输入流 读到Servlet 中 String path = “res/”+fileName ; InputStream in = getServletContext().getResourceAsStream(path) ; //通过输出流 将刚才已转为输入流的文件输出给用户 ServletOutputStream out = response.getOutputStream(); byte[] bs = new byte[1024] ; int len = -1 ; while( ( len=in.read(bs) ) != -1 ) { out.write(bs,0,len);; } out.close(); in.close(); }

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); }

    }

    Processed: 0.030, SQL: 9