说明:本篇文章的需求是下载功能,如果是图片的话就预览效果,如果不是图片就下载
SpringMVC框架搭建和上传多文件上传请参考之前的播客
SpringMVC框架搭建 http://blog.csdn.net/liqingwei168/article/details/79137801
文件上传 http://blog.csdn.net/liqingwei168/article/details/79148388
多文件上传 http://blog.csdn.net/liqingwei168/article/details/79148989
接下来我们开始写代码 Controller中代码
@RequestMapping(value="/downFileTwo") public void downloadtwo(HttpServletRequest request, HttpServletResponse response, @RequestParam("id") String id, Model model)throws Exception { UpDownQuery query = new UpDownQuery(); query.setId(id); List<UpDown> upDownList = upDownService.findUpDownAll(query); //前面三行代码是从数据库里查询文件路径 if(upDownList.size()==1){ //下载文件路径 String path = upDownList.get(0).getUrl()+"/"; //文件名称 String allName = upDownList.get(0).getAllName(); InputStream inputStream = new FileInputStream(path+allName); if(inputStream!=null){ try { BufferedImage image = ImageIO.read(inputStream); //判断是否是图片 1.是预览 2.下载 if(image!=null){ //打开本地文件流 //激活下载操作 response.setContentType("image/jpeg"); ImageIO.write(image, "JPEG", response.getOutputStream()); }else { response.setContentType("application/force-download"); String downloadFielName = new String(allName.getBytes("UTF-8"),"iso-8859-1"); response.addHeader("Content-Disposition","attachment;fileName=" + downloadFielName);// 设置文件名 OutputStream outputStream = response.getOutputStream(); byte[] bytes = new byte[2048]; int len = 0; while ((len = inputStream.read(bytes))>0){ outputStream.write(bytes,0,len); } inputStream.close(); outputStream.close(); } } catch (Exception e){ response.setContentType("text/html;charset=UTF-8"); response.getWriter().write("系统错误或文件已被删除!请联系管理员!"); throw e; } }else { response.setContentType("text/html;charset=UTF-8"); response.getWriter().write("系统错误或文件已被删除!请联系管理员!"); } } }list.jsp页面
<%@ page contentType="text/html;charset=UTF-8" language="java" %> <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> <!DOCTYPE html> <html> <head> <title>下载功能在线调试</title> </head> <body> <c:forEach items="${upDownList}" var="upDownList"> <a target="_blank" href="/upload/downFile?id=${upDownList.id}">${upDownList.firstName}下载一</a> <a target="_blank" href="/upload/downFileTwo?id=${upDownList.id}">下载二</a><br> </c:forEach> </body> </html>到此下载功能就完成了