下载(W11DownLoadServlet.java和downlist.jsp和Downservlet.java)

:(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();

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 1. Java基础部分 基础部分的顺序:基本语法,类相关的语法,内部类的语法,继承相关的语法,异常的语法,线程的语...
    子非鱼_t_阅读 31,805评论 18 399
  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 135,156评论 19 139
  • 本文包括:1、文件上传概述2、利用 Commons-fileupload 组件实现文件上传3、核心API——Dis...
    廖少少阅读 12,656评论 5 91
  • 1、不安全的随机数生成,在CSRF TOKEN生成、password reset token生成等,会造成toke...
    nightmare丿阅读 3,797评论 0 1
  • 突然间就天昏地暗 莫名的失落感((٩(//̀Д/́/)۶))
    我的老天鹅阅读 144评论 1 0