---
title: "11级_Java_曹建波 11.30 文件下载"
author: "mywebcode"
date: "2012-11-30T21:11:00Z"
tags: []
slug: "11-java-11-30"
draft: false
lastmod: "2013-05-08T10:17:25Z"
id: 1862561
url: "https://mywebcode.iteye.com/blog/1862561"
---

文件下载

因为要下载的文件可以是各种类型的文件，所以要将文件传送给客户端，其相应内容应该被当做二进制来处理，所以应该调用方法返回 ServeltOutputStream对象来向客户端写入文件内容。

下载案例

遍历上传目录下的所有文件显示给用户，并允许用户完成下载。

（读取某一个文件夹下的所有的文件，存到集合里面List，再存到request作用域范围中）ListFileServelt—（将所有的文件列表显示）Listfiles.jsp-----DownloaServlet.java

private String id;

private String savename; //上传文件的名称，文件的uuid名

private String realName; //上传文件的真实名称

private String savepath; //记住文件的位置

private Date uptime; //文件的上传时间

private String description; //文件的描述

private String username; //上传人

ListFileServlet

package com.hbsi.servlet;

import java.io.File;

import java.io.IOException;

import java.io.PrintWriter;

import java.util.HashMap;

import java.util.Map;

import javax.servlet.ServletException;

import javax.servlet.http.HttpServlet;

importjavax.servlet.http.HttpServletRequest;

importjavax.servlet.http.HttpServletResponse;

public class ListFileServlet extendsHttpServlet {

publicvoid doGet(HttpServletRequest request, HttpServletResponse response)

throwsServletException, IOException {

Stringsavepath = this.getServletContext().getRealPath(

"/WEB-INF/upload");

Mapmap = new HashMap();

listFiles(newFile(savepath), map);

request.setAttribute("map",map);

request.getRequestDispatcher("/listfile.jsp")

.forward(request,response);

}

privatevoid listFiles(File file, Map map) {

if(file.isFile()) {

Stringuuidname = file.getName(); // uuid\_a\_1\_3\_3.txt

Stringrealname = uuidname.substring(uuidname.indexOf("\_") + 1);

map.put(uuidname,realname);

}else {

File\[]files = file.listFiles();

for(File f : files) {

listFiles(f,map);

}

}

}

publicvoid doPost(HttpServletRequest request, HttpServletResponse response)

throwsServletException, IOException {

doGet(request,response);

}

}

DownloadServlet

package com.hbsi.servlet;

import java.io.File;

import java.io.FileInputStream;

import java.io.IOException;

import java.io.OutputStream;

import java.io.PrintWriter;

import java.net.URLEncoder;

import javax.servlet.ServletException;

import javax.servlet.http.HttpServlet;

importjavax.servlet.http.HttpServletRequest;

importjavax.servlet.http.HttpServletResponse;

public class DownloadServlet extendsHttpServlet {

publicvoid doGet(HttpServletRequest request, HttpServletResponse response)

throwsServletException, IOException {

Stringfilename = request.getParameter("filename");

filename= new String(filename.getBytes("iso8859-1"), "utf-8");

System.out.println(filename);

Stringsavepath = this.getFileSavePath(this.getRealName(filename));

Filef = new File(savepath + "\\\\" + filename);

if(!f.exists()) {

request.setAttribute("message","下载的资源不存在");

request.getRequestDispatcher("/message.jsp").forward(request,response);

}

response.setHeader("content-disposition","attachment;filename="+ URLEncoder.encode(this.getRealName(filename),"UTF-8"));

FileInputStreamin = new FileInputStream(f);

byte\[]buf = new byte\[1024];

intlen = 0;

OutputStreamout = response.getOutputStream();

while((len = in.read(buf)) &gt; 0) {

out.write(buf,0, len);

}

in.close();

}

publicString getFileSavePath(String filename) {

intdir1 = filename.hashCode() & 0xf;

intdir2 = (filename.hashCode() &gt;&gt; 4) & 0xf;

Stringsavepath = this.getServletContext().getRealPath("/WEB-INF/upload")+"\\\\" + dir1 + "\\\\" + dir2;

returnsavepath;

}

publicString getRealName(String filename) {

StringrealName = filename.substring(filename.indexOf("\_") + 1);

returnrealName;

}

publicvoid doPost(HttpServletRequest request, HttpServletResponse response)

throwsServletException, IOException {

doGet(request,response);

}

}