在JavaWeb中实现遍历指定目录图片并实现下载功能

5,776次阅读
21 条评论

共计 3309 个字符,预计需要花费 9 分钟才能阅读完成。

前言

在 JavaWeb(JSP)中实现资源下载功能只需要在响应头上加入 content-disposition 响应类型即可,类型的值为attachment;filename= 文件名,这样就可以实现下载功能。
在 JavaWeb 中实现遍历指定目录图片并实现下载功能

正文

首先,我们需要一个引导页面,在引导页面中将指定的目录下的图片全部显示出来,然后输出到页面中,并提供下载按钮。代码如下:

<%@ page import="java.io.File" %>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Download2</title>
    <style type="text/css">
        a.down{
            color: #FFF;
            width: 150px;
            height: 30px;
            display: inline-block;
            line-height: 30px;
            background-color: #00b4ef;
            text-decoration: none;
            border-radius: 5px;
        }
        a.down:hover{opacity:0.5;}
        .down_img{
            border:1px dashed #ddd;
            border-radius: 5px;
        }
        .downbox{
            border:1px solid #ddd;
            padding: 10px;
            width: 260px;
            height:160px;
            box-shadow: 0 1px 3px rgba(41, 41, 41, 0.95);
            display: inline-block;
            margin:10px;
        }
    </style>
</head>
<body>
<%!
    String[] checkNames = {"jpg","png","gif"}; // 可显示与下载的图片类型
    public boolean check(String name){String[] s = name.split(":");
        int len = s.length;
        for (String names:checkNames) {if(name.equals(s[len-1])){return true;}
        }
        return false;
    }

%>
<%

    String path = request.getServletContext().getRealPath("/images");
    File file = new File(path);
    File[] files = file.listFiles();
    for (File f:files) {if(check(f.getName())){
            out.print("<div class=\"downbox\">\n" +
                    "<center>\n" +
                    "<img src=\"../images/"+f.getName()+"\"class=\"down_img\"alt=\" 加载中...\"width=\"200px\"height=\"105px\">\n" +
                    "</center>\n" +
                    "<br>\n" +
                    "<center><a href=\"/cn/exercise/Download2?download="+f.getName()+"\"class=\"down\"> 下载此图 </a></center>\n" +
                    "</div>");
        }
    }
%>
</body>
</html>
接着,在点击下载的时候,会向服务器的 Servlet 类传递一个参数,然后服务器根据传递进行的参数值做出响应,实现对参数指定图片进行下载。
package cn.exercise;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
@WebServlet(name = "Download2", urlPatterns = {"/cn/exercise/Download2"})
public class Download2 extends HttpServlet {protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {this.doGet(request, response);
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {request.setCharacterEncoding("utf-8");
        response.setCharacterEncoding("utf-8");
        String imgName = request.getParameter("download");
        /*imgName = new String(imgName.getBytes("iso8859-1"),"utf-8");*/
        String path = "/images/"+imgName;
       /* System.out.println(path);*/
        new Tools().fileWriter(path,response);
    }
}
由上 Servlet 类代码可以看出,它将参数传递给了工具类中的 fileWriter 方法,这样可以实现业务逻辑分离,然后我们可以在该方法里面进行文件读入与写出,接着做出对客户端的响应。
package cn.exercise;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;

class Tools {void fileWriter(String path, HttpServletResponse response) throws IOException {response.setCharacterEncoding("utf-8");
        path = "../../"+path;
        path = this.getClass().getClassLoader().getResource(path).getPath();
        File file = new File(path);
        InputStream in = new FileInputStream(file);
        OutputStream out = response.getOutputStream();
        response.setHeader("content-disposition","attachment;filename="+ URLEncoder.encode(file.getName(),"utf-8"));
        byte[] b = new byte[1024];
        int length = 0;
        while((length=in.read(b))!=-1){out.write(b,0,length);
        }
        out.close();
        in.close();}
}
到这里,遍历指定目录下的图片并实现下载功能就实现了。运行截图如下:

在 JavaWeb 中实现遍历指定目录图片并实现下载功能


在 JavaWeb 中实现遍历指定目录图片并实现下载功能

后记

在该功能实现中,只进行对指定目录下的一级目录图片进行下载,没有进行对多级目录下的图片进行下载,原因是只循环了一级目录下的所有文件并进行了判断是否是指定的图片类型,没有进行多级循环(递归)来判断。另若该代码中存在 Bug 或者还有别的更好的实现方法,可以在下方评论区发表您的看法!在 JavaWeb 中实现遍历指定目录图片并实现下载功能
正文完
使用官方微信小程序体验更多功能
post-qrcode
 3
憧憬Licoy
版权声明:本站原创文章,由 憧憬Licoy 2016-11-15发表,共计3309字。
转载说明:除特殊说明外本站文章皆由CC-4.0协议发布,转载请注明出处。
评论(21 条评论)
今天星期二 评论达人 LV.1
2017-03-21 20:53:18 回复

大神您好,按照您的代码建了一个工程,出现错误:HTTP Status 500 – An exception occurred processing JSP page /Download2.jsp at line 55
jsp页面代码和上面一样的,行数也一样。请问这该怎么办?

 Windows  Chrome  中国江西省南昌市电信
    憧憬Licoy 博主
    2017-03-21 21:10:20 回复

    @今天星期二 你输出53行的file的路径看看是否正确,可能是没有找到目标文件报异常了

     Windows  Chrome
      今天星期二 评论达人 LV.1
      2017-03-21 21:54:44 回复

      @憧憬Licoy 这个问题解决了,直接把 File file = new File(path);中path改成路径。。但是图片一直在加载中,下载时也会报错。还是感谢博主

       Windows  Chrome  中国江西省南昌市电信
信阳毛尖 评论达人 LV.1
2016-12-02 18:01:16 回复

:razz: :razz: :razz: 晕了

 Windows  Chrome  中国广东省惠州市电信
xema 评论达人 LV.3
2016-11-18 19:16:09 回复

看过这种厉遍下载的,不过多数都是python~

 Windows  Firefox  中国广东省揭阳市电信
卢松松博客 评论达人 LV.1
2016-11-17 20:32:43 回复

确实不懂了

 Windows  Chrome  中国河北省廊坊市联通
ixwebhosting 评论达人 LV.1
2016-11-17 15:30:53 回复

兄弟,交换链接吗?

 Windows  Chrome  中国江苏省苏州市电信
王贱贱 评论达人 LV.1
2016-11-17 14:45:27 回复

这个就没办法了,真的看不懂

 Windows  Firefox  中国湖北省武汉市电信
企业管理咨询 评论达人 LV.1
2016-11-17 12:12:35 回复

装作看得懂的样子来评论下

 Windows  Firefox  中国广东省深圳市电信
马超金博客 评论达人 LV.1
2016-11-16 12:22:10 回复

太深奥了,呵呵

 Android  Chrome  中国广东省深圳市联通
玩游戏赚钱 评论达人 LV.1
2016-11-16 11:55:32 回复

感谢分享,欢迎回访

 Windows  Chrome  中国浙江省温州市电信