---
title: "文件下载的基本实现"
author: "ducklsl"
date: "2013-04-05T23:27:06Z"
tags: ["Java", "Servlet"]
categories: ["编程语言"]
slug: "untitled"
draft: false
lastmod: "2013-04-06T22:07:27Z"
id: 1842546
url: "https://changluo.iteye.com/blog/1842546"
---

可以实现文件下载的方式有各种各样的，可以直接在浏览器打开，也可以作为附件进行下载，这里面的最主要的部分其实就是对HTTP响应头content-disposition的控制。服务器设置响应头，告诉浏览器该以何种的方式(attachment或者inline)以及何种内容类型(response.setContentType("..."))打开文件。 1)显示可以下载文件列表Servlet\[code="java"] public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doPost(request,response); } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { List fileList = getFileName("F:\\\\downloadtest");//指定文件存放位置 request.setAttribute("lists", fileList);//设置到request中 request.getRequestDispatcher("list.jsp").forward(request, response);//将请求转发 } /\** * 列出path路径下可以下载的文件名 * @param path * @return \*/ public static List getFileName(String path){ List fileNames =new ArrayList(); File source = new File(path); if(source.isDirectory()&&source.exists()){//判断是否存在以及是否是一个目录 File\[] files = source.listFiles(); for(File file:files){ fileNames.add(file.getName());//获得文件目录 } } return fileNames; }\[/code]2)list.jsp界面代码，用来显示可以现在的文件名\[code="java"] &lt;% List fileNames =(List) request.getAttribute("lists"); for(String name:fileNames){ %&gt; \[url=DownloadServlet?filename=&lt;%=name %&gt;]&lt;%=name%&gt;\[/url]  
&lt;% } %&gt; \[/code]3)DownloadServlet实现文件的下载\[code="java"]public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doPost(request, response); } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { request.setCharacterEncoding("GB2312"); String serverPath = "F:\\\\downloadtest"; String fileName = new String(request.getParameter("filename").getBytes( "ISO-8859-1"), "GB2312");//get提交的方式去乱码 String fullPath = serverPath + "\\\\" + fileName; System.out.println(fullPath); File file = new File(fullPath); //设置相应头， //attachment是以附件的方式下载，并且文件名为filename后面的字符串的值 response.setHeader("content-disposition", "attachment;filename=" + new String(fileName.getBytes("GB2312"), "ISO-8859-1"));//去除文件下载时显示名称乱码 InputStream in = null; OutputStream output = null; try { in = new FileInputStream(file); int length = 0; byte buffer\[] = new byte\[1024]; output = response.getOutputStream(); while ((length = in.read(buffer)) != -1) {// 如果使用in.read()方法，仅仅可以下载到文件，而不能得到文件的内容 output.write(buffer, 0, length); } } catch (Exception e) { e.printStackTrace(); } finally { in.close(); output.close(); } }\[/code]在此Servlet中，主要的实现也是依靠对文件的IO操作，其中response.getOutputStream返回的实际类型为ServletOutputStream，它是OutputStream的一个子类，API中说道“Provides an output stream for sending binary data to the client.” 以上的这种方式，是告诉浏览器以附件的方式打开此文件，另外还有一种就是在线的方式打开文件\[code="java"]//可以设置为浏览器直接打开，不使用附件的方式下载； response.setHeader("content-disposition", "inline;filename="+ new String(fileName.getBytes("GB2312"), "ISO-8859-1"));\[/code]经过测试，如果使用浏览器直接打开的话，是可以正常显示文件中的内容的(特殊文件除外，如word等，txt、jpeg等文件可以直接打开)，而且office2003以上版本就会提示以压缩文件的方式进行打开。\[color=red]这点谜团有待解开，有知道的朋友可以告知一下谢谢\[/color]