前言
在JavaWeb(JSP)中实现资源下载功能只需要在响应头上加入content-disposition
响应类型即可,类型的值为attachment;filename=文件名
,这样就可以实现下载功能。
正文
首先,我们需要一个引导页面,在引导页面中将指定的目录下的图片全部显示出来,然后输出到页面中,并提供下载按钮。代码如下:
<%@ 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(); } }
到这里,遍历指定目录下的图片并实现下载功能就实现了。运行截图如下:
后记
[v_tips]在该功能实现中,只进行对指定目录下的一级目录图片进行下载,没有进行对多级目录下的图片进行下载,原因是只循环了一级目录下的所有文件并进行了判断是否是指定的图片类型,没有进行多级循环(递归)来判断。另若该代码中存在Bug或者还有别的更好的实现方法,可以在下方评论区发表您的看法!
[/v_tips]
大神您好,按照您的代码建了一个工程,出现错误:HTTP Status 500 – An exception occurred processing JSP page /Download2.jsp at line 55
jsp页面代码和上面一样的,行数也一样。请问这该怎么办?
@今天星期二 你输出53行的file的路径看看是否正确,可能是没有找到目标文件报异常了
@憧憬Licoy 这个问题解决了,直接把 File file = new File(path);中path改成路径。。但是图片一直在加载中,下载时也会报错。还是感谢博主
@今天星期二 应该是路径不正确导致的。
@信阳毛尖 为什么晕了
看过这种厉遍下载的,不过多数都是python~
@xema 关键的是我不会python
@憧憬Licoy 会Java就很不得了的了
@xema 现在会一种语言要精才行
确实不懂了
@卢松松博客 松松大神
兄弟,交换链接吗?
@ixwebhosting 不好意思,贵站的内容与本站友链交换规则不符。
这个就没办法了,真的看不懂
@王贱贱 :arrow: 好吧
装作看得懂的样子来评论下
太深奥了,呵呵
@马超金博客 发展方向不同。
感谢分享,欢迎回访
@玩游戏赚钱 好的
SpringCloud使用Zuul出现“Forwarding error”错误解决方法
Chatroulette-全世界随机视频聊天网站
IntelliJ IDEA下将JavaWeb打包成war包并发布到tomcat步骤说明
LiRecord留言板系统V2.0正式版发布
SpringBoot打包成war包并放置在tomcat运行
SpringBoot+Shiro整合进行登录验证与权限控制
多风格自适应WordPress主题Puock正式开源!
非大众版WordPress纯代码实现阅读量统计
面包多WordPress插件 – 把你的文章变成付费版
git reset —hard后暂存区代码跑哪儿去了?
选择表情
分享至