下载(W11DownLoadServlet.java和downl

2017-01-04  本文已影响0人  康明

:(W11DownLoadServlet.java和downlist.jsp和Downservlet.java)中介绍

1)  DownLoadServlet.java中有关遍历本地的资源,以及要转发到downlist.jsp中展示,DownServlet.java中进行下载代码的实现

1.1)DownLoadServlet.java中有关遍历本地的资源:

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {// TODO Auto-generated method stub//response.getWriter().append("Served at: ").append(request.getContextPath());//保存文件的完整名称(key)和简化名称(value)MapfileNames = new HashMap<>();

//获取目录中所有文件

String path = "D:/upload";

File dirFile = new File(path);

//没有判断文件夹的情况。

if (dirFile!=null||dirFile.isDirectory()) {

String[] list = dirFile.list();

if (list!=null&&list.length>0) {

for (int i = 0; i < list.length; i++) {

String fullName = list[i];

String shortName = fullName.substring(fullName.indexOf("-")+1);

fileNames.put(fullName, shortName);

}

}

}

request.setAttribute("fileMap", fileNames);

//通过转发调到界面

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

}

1.2)转发到downlist.jsp中展示

1.3)DownServlet.java中进行下载代码的实现

:

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

// TODO Auto-generated method stub

//response.getWriter().append("Served at: ").append(request.getContextPath());

String fileName = request.getParameter("name");

//处理get方式的中文乱码

fileName = new String(fileName.getBytes("iso-8859-1"),"utf8");

String path = "D:/upload";

//获取输入流

InputStream in = new FileInputStream(new File(path,fileName));

//对URL的处理,不处理文件名中 中文会变成“ ”等形式

fileName=URLEncoder.encode(fileName,"utf8");

//设置下载的响应头,请求的内容存为文件时,需要一个默认的文件名

response.setHeader("content-disposition", "attachment;fileName="+fileName);

//获得响应的输出流

ServletOutputStream out = response.getOutputStream();

//将输入流中的数据通过输出流进行保存

byte[] buff = new byte[1024];

int len=-1;

while ((len=in.read(buff))!=-1) {

out.write(buff,0,len);

}

out.close();

in.close();

}

注:********

//获取输入流

InputStream in = new FileInputStream(new File(path,fileName));

//对URL的处理,不处理文件名中 中文会变成“ ”等形式

fileName=URLEncoder.encode(fileName,"utf8");

//设置下载的响应头,请求的内容存为文件时,需要一个默认的文件名

response.setHeader("content-disposition", "attachment;fileName="+fileName);



//获得响应的输出流

ServletOutputStream out = response.getOutputStream();

上一篇下一篇

猜你喜欢

热点阅读