1.1.1. 实现思路

1.读取本地的文件

2.将读取的文件显示到页面上

3.页面点击下载,下载文件

4.解决中文乱码问题

 

1.1.2. 示例代码

1.创建一个文件列表

<%@ page language="java" contentType="text/html; charset=UTF-8"

    pageEncoding="UTF-8"%>

<%@taglib prefix="c"  uri="http://java.sun.com/jsp/jstl/core"%>    

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<html>

<head>

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">

<title>Insert title here</title>

<script type="text/javascript">

  /*

    将路径的参数编码.发送到后台方法在解码

  */

  function download(val){

  //将参数路径编码,Base64

  var filename=encodeURI(val);

  //escape防止浏览器转义导致路径编码无法解释

  var path="${pageContext.request.contextPath }/download.mvc?fname="+escape(filename);

  //跳转到下载的路径

  window.location.href=path;

  }

</script>

</head>

<body>

文件列表

<table border="1">

  <tr>

    <td>文件名</td>

    <td>下载</td>

  </tr>

  <c:forEach var="fileName" items="${fileNames }">

  <tr>

    <td>${fileName}</td>

    <td><a href="javascript:download('${fileName}')">下载</a></td>

  </tr>

  </c:forEach>

</table>

</body>

</html>

2.后台代码

package cn.lxm.controller;

 

import java.io.File;

import java.io.IOException;

import java.net.URLDecoder;

import java.util.Arrays;

 

import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;

 

import org.apache.commons.io.FileUtils;

import org.springframework.stereotype.Controller;

import org.springframework.web.bind.annotation.RequestMapping;

 

@Controller

public class DownloadController {

/**

 * 文件下载首先要有一个下载列表

 * @return

 */

@RequestMapping(value="file-list")

public String listFile(HttpServletRequest request){

//1.读取文件夹 d:\dir

File dir =new File("d:/dir");

//2.获得文件夹里面文件名

String[] fileNames = dir.list();

System.out.println(Arrays.toString(fileNames));

//3.将文件名放在request

request.setAttribute("fileNames", fileNames);

return "/file-list.jsp";

}

 

/**

 * 文件下载

 * 所谓的文件下载就是将文件写入到HttpServletResponse里面

 */

@RequestMapping(value="download")

public void download(String fname,HttpServletResponse response){

try {

//解码

fname=URLDecoder.decode(fname, "UTF-8");

System.out.println(fname+"-----");

//1.通过文件名获得文件

File file=new File("d:/dir/"+fname);

//将文件变成流,写入到HttpServletResponse的输出流里面

//使用commons-io-2.2.jar的文件处理类实现,将文件转成一个byte[]字节流

 byte[] array=null;

 

array = FileUtils.readFileToByteArray(file);

//在response输出之前,设置输出的格式

//默认不支持中文,new String(fname.getBytes(),"ISO-8859-1"),转义中文编码

response.addHeader("Content-Disposition", "attachment;filename="+new String(fname.getBytes(),"ISO-8859-1"));

//将文件写入到response的输出流

response.getOutputStream().write(array);

} catch (IOException e) {

// TODO Auto-generated catch block

e.printStackTrace();

}

}

}