java+swiper实现图片预览(不做io操作)

需求:实现图片的预览。图片存于服务器的本地磁盘上不是在数据库中。预览的时候不做io操作 以降低页面的负载。

插件 :swiper  自行百度下载注意下载web版的。

以下是contoller的代码:

  1.以下代码有个偷懒(low)的地方,也是数据表的设计缺陷没有存文件的类型 所以直接用文件名的后缀判断是否是图片。

  2.controller的作用就是把图片在服务器上的绝对路径返回给jsp ,如C://pic/helloworld.jpg;

package com.main.controller;

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import com.common.CommonUtil;
import com.common.DocConverter;
import com.main.pojo.Attachment;
import com.main.service.AttachmentService;

/**
 * 附件预览controller 基于OppenOfiice实现
 * 
 * @author lwh 2018年9月21日 下午3:28:38
 */
@Controller
@RequestMapping("/attachmentPreview")
public class AttachmentPreviewController {
    @Resource
    private AttachmentService attachmentService;

    /**
     * 附件预览(支持excel word pdf txt ppt pdf png gif bpm jpg) lwh 2018年10月11日
     * 下午4:25:55
     * 
     * @param id
     *            附件
     * @param request
     * @param response
     * @return
     */
    @RequestMapping("/filePreview/{id}")
    public String toFilePreviewPage(@PathVariable String id, HttpServletRequest request, HttpServletResponse response) {
        boolean res = false;
        String contexPath = request.getSession().getServletContext().getRealPath("/");
        boolean isPic = false;// 判断是否为图片预览 ·
        try {

            Attachment att = attachmentService.getById(id);
            if (isPicture(att.getFileName())) {
          //图片预览 List
<Attachment> attList = new ArrayList<>(); attList.add(att); // TODO /* * * 为了避免预览时大量下载造成压力故图片预览的时候 不做图片下载IO操作, 通过配置虚拟目录读取,将以下配置加入 * tomcat的server.xml的<host>中 <Context path="/attachment" * docBase="E:\apache-tomcat-7.0.90\financeAttatch\" * docBase为tomcat下的附件存放目录的绝对路径 reloadable="true"></Context> * 如果配置nginx或者其他负载均衡等。。。 需要将虚拟目录加入其配置文件,否则可能会被拦截,导致图片无法显示 */ isPic = true; List<Attachment> attListTemp = attachmentService.getPictureAttachment(att.getAsocciateId(), att.getId()); /* * 设置当前点击图片为第一张显示 */ if (attListTemp != null && attListTemp.size() > 0) { for (Attachment attachment : attListTemp) { attList.add(attachment); } } request.setAttribute("list", attList); } else { // TODO // 服务器上需要安装openoffice 并启动服务. DocConverter d = new DocConverter(att.getFileUrl() + File.separator + att.getFileName(), contexPath + "/resources/file/ftp", contexPath + "/WEB-INF/classes"); delete(contexPath + "/resources/file/ftp"); // 调用conver方法开始转换,先执行doc2pdf()将office文件转换为pdf;再执行//pdf2swf()将pdf转换为swf; res = d.conver(); String fn = d.getswfPath(); if (CommonUtil.isNotNullStr(fn)) { request.setAttribute("swfPath", fn.substring(fn.lastIndexOf("/"), fn.length())); } } } catch (Exception e) { request.setAttribute("errorMsg", e.getMessage()); e.printStackTrace(); } if (res == false && isPic == false) { // 类型不支持预览。 return "attach/Cantpreview"; } if (isPic) { return "attach/PicPreview";// 图片预览 } return "attach/FilePreview";// 文档预览 } /** * 清除临时文件夹中的文件。 */ protected boolean delete(String path) { boolean flag = false; File file = new File(path); if (!file.exists()) { return flag; } if (!file.isDirectory()) { return flag; } String[] tempList = file.list(); File temp = null; for (int i = 0; i < tempList.length; i++) { if (path.endsWith(File.separator)) { temp = new File(path + tempList[i]); } else { temp = new File(path + File.separator + tempList[i]); } if (temp.isFile()) { temp.delete(); } if (temp.isDirectory()) { delete(path + "/" + tempList[i]);// 先删除文件夹里面的文件 delete(path + "/" + tempList[i]);// 再删除空文件夹 flag = true; } } return flag; } /** * 要预览其他格式的图片,将图片的后缀加入条件即可,支持预览html img标签src="支持的图片格式" lwh 2018年10月15日 * 上午11:38:25 * * @param fileName * @return */ public boolean isPicture(String fileName) { boolean flag = false; if (fileName.endsWith(".jpg") || fileName.endsWith(".bpm") || fileName.endsWith(".png") || fileName.endsWith(".gif")) { flag = true; } return flag; } }

以下是jsp代码 用到了swiper.js 没有其他技术点,贴了就可以用了 。具体页面样式的话 可以copy一个swiper官方demo改一下就好了。

不足之处是不能放大缩小旋转等操作。笔者有写了一个带这些功能的插件,但是没有经过考验的代码 日后再贴吧。

  1 <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
  2 <%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
  3 <%
  4     String path = request.getContextPath();
  5     String basePath = request.getScheme() + "://"
  6             + request.getServerName() + ":" + request.getServerPort()
  7             + path + "/";
  8     String swfName = String.valueOf(request.getAttribute("swfPath"));
  9 %>
 10 
 11 
 12 
 13 <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
 14 <html>
 15 <head>
 16 
 17 <title>凭证录入</title>
 18 <meta http-equiv="pragma" content="no-cache">
 19 <meta http-equiv="cache-control" content="no-cache">
 20 <meta http-equiv="expires" content="0">
 21 <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
 22 <meta http-equiv="description" content="This is my page">
 23 <base href="<%=basePath%>">
 24 <link rel="stylesheet"
 25     href="<%=path%>/resources/style/record-background.css" type="text/css" />
 26 
 27 <link rel="stylesheet"
 28     href="<%=path%>/resources/style/idangerous.swiper.css" type="text/css" />
 29 <link rel="stylesheet"
 30     href="<%=path%>/resources/style/idangerous.swiper.scrollbar.css"
 31     type="text/css" />
 32 <!-- 通用的文件导入 -->
 33 <jsp:include page="/base.jsp"></jsp:include>
 34 <script type="text/javascript"
 35     src="<%=path%>/resources/ueditor/third-party/jquery-1.10.2.min.js"></script>
 36 <script type="text/javascript"
 37     src="<%=path%>/resources/script/idangerous.swiper.js"></script>
 38 <style>
 39 body {
 40     margin: 0;
 41     font-family: Arial, Helvetica, sans-serif;
 42     font-size: 13px;
 43     line-height: 1.5;
 44 }
 45 
 46 .device {
 47     width: 840px;
 48     height: 400px;
 49     padding: 30px 40px;
 50     border-radius: 20px;
 51     background: #111;
 52     border: 3px solid white;
 53     margin: 5px auto;
 54     position: relative;
 55     box-shadow: 0px 0px 5px #000;
 56 }
 57 
 58 .device .arrow-left {
 59     background: url(<%=path%>\/resources\/image\/img\/arrows.png) no-repeat
 60         left top;
 61     position: absolute;
 62     left: 10px;
 63     top: 50%;
 64     margin-top: -15px;
 65     width: 17px;
 66     height: 30px;
 67 }
 68 .device .arrow-right {
 69     background: url(<%=path%>\/resources\/image\/img\/arrows.png) no-repeat
 70         left bottom;
 71     position: absolute;
 72     right: 10px;
 73     top: 50%;
 74     margin-top: -15px;
 75     width: 17px;
 76     height: 30px;
 77 }
 78 
 79 .swiper-container {
 80     height: 400px;
 81     width: 840px;
 82 }
 83 
 84 .content-slide {
 85     padding: 20px;
 86     color: #fff;
 87 }
 88 
 89 .title {
 90     font-size: 25px; 
 91     margin-bottom: 10px;
 92 }
 93 
 94 .pagination {
 95     position: absolute;
 96     left: 0;
 97     text-align: center;
 98     bottom: 5px;
 99     width: 100%;}
100 img{ width: 100%; height: auto;max-width: 100%; display: block; } 
101 
102 .swiper-pagination-switch {
103     display: inline-block;
104     width: 10px;
105     height: 10px;
106     border-radius: 10px;
107     background: #999;
108     box-shadow: 0px 1px 2px #555 inset;
109     margin: 0 3px;
110     cursor: pointer;
111 }
112 .swiper-active-switch {
113     background: #fff;
114 }
115 </style>
116 </head>
117 <body>
118     
119     <div class="device">
120         <a class="arrow-left" href="#"></a> 
121         <a class="arrow-right" href="#"></a>
122         <div class="swiper-container">
123             <div id="picContianer" class="swiper-wrapper">
124                 <c:forEach items="${list}" var="item" varStatus="status">
125                     <div class="swiper-slide">
126                         <img src="/attachment/${item.fileName}">
127                     </div>
128                 </c:forEach>
129             </div>
130         </div>
131         <div class="pagination"></div>
132     </div>
133     <script>
134         var mySwiper = $('.swiper-container').swiper({
135             pagination : '.pagination',
136             loop : true,
137             grabCursor : true,
138             paginationClickable : true
139         });
140         $('.arrow-left').on('click', function(e) {
141             e.preventDefault()
142             var swiper = $(this).siblings('.swiper-container').data('swiper');
143             swiper.swipePrev();
144         });
145         $('.arrow-right').on('click', function(e) {
146             e.preventDefault()
147             var swiper = $(this).siblings('.swiper-container').data('swiper');
148             swiper.swipeNext();
149         });
150     </script>
151 </body>
152 </html>
View Code

javaweb项目好像没法直接访问本地磁盘(知道方法的大佬告知一声)所以使用的虚拟目录。 以下配置了解一下

将以下配置加入
                 * tomcat的server.xml的<host>中 <Context path="/attachment"
                 * docBase="E:\apache-tomcat-7.0.90\financeAttatch\"
                 * docBase为tomcat下的附件存放目录的绝对路径 reloadable="true"></Context>
                 * 如果配置nginx或者其他负载均衡等。。。 需要将虚拟目录加入其配置文件,否则可能会被拦截,导致图片无法显示
                

  两个配置文件我就不贴了 没啥难度 。

 

 

大概实现思路就是这样,不足之处请大家指出。

 

转载于:https://www.cnblogs.com/easyunion/p/9857003.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值