前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >(强烈推荐)基于SSM和BootStrap的共享云盘系统设计(项目实现:在线预览文件)

(强烈推荐)基于SSM和BootStrap的共享云盘系统设计(项目实现:在线预览文件)

作者头像
天道Vax的时间宝藏
发布2021-08-11 14:47:08
2.2K0
发布2021-08-11 14:47:08
举报
文章被收录于专栏:用户5305560的专栏

知识点:JavaScript、jQuery、SSM、IO、Ajax、layUI,JS插件使用

重 点:前后台数据交互,文件读取,数据库查询,插件的使用等

难 点:JS插件使用

内 容:登录成功后,可在线预览图片、txt、Office文档、音视频等

image.png
image.png

图1 在线预览文档

image.png
image.png

图2 在线多媒体播放功能

1. 线预览或播放

所有的在线预览或播放,均需调用index.js中的openFile()方法,根据传入的值判断是图片、文档、音频、视频等类型,代码如下所示;

代码语言:javascript
复制
/**分类型打开文件*/
function openFile(obj) {
    var fileType = $(obj).attr("filetype");
    var fileName = $(obj).text();
    var parentPath = $(obj).attr("currentPath") == null ? currentPath : $(obj).attr("currentPath");
    var url = encodeURI('currentPath='+parentPath+'&fileType='+fileType+ '&fileName='+fileName);
    if (fileType == "folder-open") {
        var prePath = $(obj).attr("prePath");
        var path = prePath + "\\" + fileName;
        getFiles(path);
        navPath(path, fileName);
    } else if(fileType.indexOf("image") >= 0){
        $(obj).attr({"href":"file/openFile.action?"+url,"data-lightbox":"test","data-title":fileName});
        return true;
    } else if(fileType.indexOf("office") >= 0){
        $.post("file/openOffice.action", {
            "currentPath" : parentPath,
            "fileType" : fileType,
            "fileName" : fileName,
        }, function(data){
            if(data.success){
                openOffice(data.data);
            }else{
                layer.msg(data.msg);
            }
        });
    } else if(fileType.indexOf("audio") >= 0){
        layer.open({
            type:2,
            title:'播放',
            content:'file/openAudioPage.action?' + url,
            shade: [0],
            area: ['440px', '120px'],
            offset: 'rb', /右下角弹出
        });
    } else if(fileType.indexOf("docum") >= 0){
        $.post("file/openFile.action", {
            "currentPath" : parentPath,
            "fileType" : fileType,
            "fileName" : fileName,
        }, function(data){
            layer.open({
                type: 1,
                area: ['720px', '570px'],
                title:false,
                scrollbar: false,
                content: '<textarea rows="50" cols="150">'+data+'</textarea>'
            });
        });
    } else if(fileType.indexOf("vido") >= 0){
        layer.open({
            type: 1,
            area: ['480px', '400px'],
            title:false,
            content: '<div id="a1"></div>'
        });
        var flashvars={
                f:'file/openFile.action?' + url,
                c:0,
                p:1,
                b:1
            };
        var params={bgcolor:'#FFF',allowFullScreen:true,allowScriptAccess:'always',wmode:'transparent'};
        CKobject.embedSWF('js/ckplayer/ckplayer.swf','a1','ckplayer_a1','480','400',flashvars,params);
        return false;
    }
    return false;
}

2. 在线预览图片和txt文档

1)点击图片、图片的文件名或txt文档名时,通过JS或Ajax向后端发出file/openFile.action请求,请求参数是由之前后端的返回数据拼接而成。部分核心代码如下所示;

代码语言:javascript
复制
$.each(data.data, function() {
    $("#"+ typeName).append('<a href="file/openFile.action?'+url+'" data-lightbox="roadtrip" title="'+this.fileName+'"><img alt="'+this.fileName+'" style="margin: 10px" src="file/openFile.action?'+url+'" width="150" height="150"></a>');
});

2)另外,此处还引入了lightbox插件,否则每次请求action后直接打开的是图片,而不是在当前页面上再弹出一个图片或文本显示框。在index.jsp的<head>标签中引入lightbox插件,代码如下所示;

代码语言:javascript
复制
<link href="${pageContext.request.contextPath }/css/lightbox.css" rel="stylesheet">
<script src="${pageContext.request.contextPath }/js/lightbox.js"></script>

3)在FileController类中添加openFile()方法,用于接受和处理在线图片/txt预览功能,代码如下所示;

代码语言:javascript
复制
/**
 * 打开文件
 * 
 * @param response
 *            响应文件流
 * @param currentPath
 *            当前路径
 * @param fileName
 *            文件名
 * @param fileType
 *            文件类型
 */
@RequestMapping("/openFile")
public void openFile(HttpServletResponse response, String currentPath,String fileName, String fileType) {
    try {
        fileService.respFile(response, request, currentPath, fileName, fileType);
    }catch (IOException e) {
        e.printStackTrace();
    }
}

4)在FileService类中添加respFile()方法,通过Apache的IOUtils.copy()方法对当前图片/txt文件进行读写。前端将为txt文档传入对应的“docum”标识;当type变量为“docum”的时,则需要再做一次编码装换,以防止文本乱码,代码如下所示;

代码语言:javascript
复制
public void respFile(HttpServletResponse response, HttpServletRequest request, String currentPath, String fileName,String type) throws IOException {
    File file = new File(getFileName(request, currentPath), fileName);
    InputStream inputStream = new FileInputStream(file);
    if ("docum".equals(type)) {
        response.setCharacterEncoding("UTF-8");
        IOUtils.copy(inputStream, response.getWriter(), "UTF-8");
    } else {
        IOUtils.copy(inputStream, response.getOutputStream());
    }
}

3. Office文档在线预览或播放

所有的在线预览或播放,均需调用index.js中的openFile()方法,根据传入的值判断是图片、文档、音频、视频等类型,代码如下所示;

代码语言:javascript
复制
function openFile(obj) {
    var fileType = $(obj).attr("filetype");
    var fileName = $(obj).text();
    var parentPath = $(obj).attr("currentPath") == null ? currentPath : $(obj).attr("currentPath");
    var url = encodeURI('currentPath='+parentPath+'&fileType='+fileType+ '&fileName='+fileName);
    if (fileType == "folder-open") {
        var prePath = $(obj).attr("prePath");
        var path = prePath + "\\" + fileName;
        getFiles(path);
        navPath(path, fileName);
    } else if(fileType.indexOf("image") >= 0){
        $(obj).attr({"href":"file/openFile.action?"+url,"data-lightbox":"test","data-title":fileName});
        return true;
    } else if(fileType.indexOf("office") >= 0){
        $.post("file/openOffice.action", {
            "currentPath" : parentPath,
            "fileType" : fileType,
            "fileName" : fileName,
        }, function(data){
            if(data.success){
                openOffice(data.data);
            }else{
                layer.msg(data.msg);
            }
        });
    } else if(fileType.indexOf("audio") >= 0){
        layer.open({
            type:2,
            title:'播放',
            content:'file/openAudioPage.action?' + url,
            shade: [0],
            area: ['440px', '120px'],
            offset: 'rb', /右下角弹出
        });
    } else if(fileType.indexOf("docum") >= 0){
        $.post("file/openFile.action", {
            "currentPath" : parentPath,
            "fileType" : fileType,
            "fileName" : fileName,
        }, function(data){
            layer.open({
                type: 1,
                area: ['720px', '570px'],
                title:false,
                scrollbar: false,
                content: '<textarea rows="50" cols="150">'+data+'</textarea>'
            });
        });
    } else if(fileType.indexOf("vido") >= 0){
        layer.open({
            type: 1,
            area: ['480px', '400px'],
            title:false,
            content: '<div id="a1"></div>'
        });
        var flashvars={
            f:'file/openFile.action?' + url,
            c:0,
            p:1,
            b:1
        };
        var params={bgcolor:'#FFF',allowFullScreen:true,allowScriptAccess:'always',wmode:'transparent'};
        CKobject.embedSWF('js/ckplayer/ckplayer.swf','a1','ckplayer_a1','480','400',flashvars,params);
        return false;
    }
    return false;
}

4. 在线预览office文档

1)当点击的类型是office类型时,将以post方式向服务端file/openOffice.action发出请求;在FileController类中增加openOffice()方法,完成前端所发出的请求,代码如下所示;

代码语言:javascript
复制
/**
 * 打开文档
 * 
 * @param currentPath
 *            当面路径
 * @param fileName
 *            文件名
 * @param fileType
 *            文件类型
 * @return Json对象(文件Id)
 */
@RequestMapping("/openOffice")
public @ResponseBody Result<String> openOffice(String currentPath,
    String fileName, String fileType) {
    try {
        String openOffice = fileService.openOffice(request, currentPath,fileName);
        if (openOffice != null) {
            Result<String> result = new Result<>(505, true, "打开成功");
            result.setData(openOffice);
            return result;
        }
        return new Result<>(501, false, "打开失败");
    } catch (Exception e) {
        e.printStackTrace();
        return new Result<>(501, false, "打开失败");
    }
}

2)在FileService类中添加openOffice()方法,通过FileUtils中的MD5()方法,将传入的文件名处理为数据库中所对应的officeMD5,代码如下所示;

代码语言:javascript
复制
/**
 * 打开文档文件
 * 
 * @param request
 * @param currentPath
 * @param fileName
 * @return
 * @throws Exception
 */
public String openOffice(HttpServletRequest request, String currentPath, String fileName) throws Exception {
    return officeDao.getOfficeId(FileUtils.MD5(new File(getFileName(request, currentPath), fileName)));
}

其中,FileUtile类中提供MD5()方法,代码如下所示;

代码语言:javascript
复制
public static String MD5(File file){
    byte[] bys = null;
    try {
        bys = org.apache.commons.io.FileUtils.readFileToByteArray(file);
        return DigestUtils.md5DigestAsHex(bys).toUpperCase();
    } catch (IOException e) {
        e.printStackTrace();
        return null;
    }
}

3)在OfficeDao.xml文件中添加SQL语句,用于根据id查询文件ID信息,代码如下所示;

代码语言:javascript
复制
<select id="getOfficeId" parameterType="java.lang.String" resultType="java.lang.String">
    select officeid from office where officeMd5 = #{officeMd5}
</select>

4)从后台获取云文档的id成功后,再调用index.js中的openOffice()方法,通过云的文档API接口,打开传入id所对应的office文档。部分核心代码如下所示;

代码语言:javascript
复制
function openOffice(id){
    layer.open({
        type: 1,
        zIndex : 80,
        area: ['auto','600px'],
        offset: '10px',
        title:false,
        content: '<div id="officeContent"></div>'
    });
    var option = {
        docId: id,
        token: 'TOKEN',
        host: 'BCEDOC',
        serverHost: 'http://doc.bj.baidubce.com',
        width: 600, /文档容器宽度
        ready: function (handler) {  / 设置字体大小和颜色, 背景颜色                   handler.setFontSize(1);
            handler.setBackgroundColor('#000');
            handler.setFontColor('#fff');
        },
        flip: function (data) {    / 翻页时回调函数, 可供客户进行统计等
            console.log(data.pn);
        },
        fontSize:'big',
        toolbarConf: {
            zoom: false,
            page: false, /上下翻页箭头图标
            pagenum: false, /几分之几页
            full: false, /是否显示全屏图标,点击后全屏
            copy: true, /是否可以复制文档内容
            position: 'center',/ 设置 toolbar中翻页和放大图标的位置
        } /文档顶部工具条配置对象,必选
    };
    new Document('officeContent', option);
}

5. 音视频线预览或播放

所有的在线预览或播放,均需调用index.js中的openFile()方法,根据传入的值判断是图片、文档、音频、视频等类型,代码如下所示;

代码语言:javascript
复制
function openFile(obj) {
    var fileType = $(obj).attr("filetype");
    var fileName = $(obj).text();
    var parentPath = $(obj).attr("currentPath") == null ? currentPath : $(obj).attr("currentPath");
    var url = encodeURI('currentPath='+parentPath+'&fileType='+fileType+ '&fileName='+fileName);
    if (fileType == "folder-open") {
        var prePath = $(obj).attr("prePath");
        var path = prePath + "\\" + fileName;
        getFiles(path);
        navPath(path, fileName);
    } else if(fileType.indexOf("image") >= 0){
        $(obj).attr({"href":"file/openFile.action?"+url,"data-lightbox":"test","data-title":fileName});
        return true;
    } else if(fileType.indexOf("office") >= 0){
        $.post("file/openOffice.action", {
            "currentPath" : parentPath,
            "fileType" : fileType,
            "fileName" : fileName,
        }, function(data){
            if(data.success){
                openOffice(data.data);
            }else{
                layer.msg(data.msg);
            }
        });
    } else if(fileType.indexOf("audio") >= 0){
        layer.open({
            type:2,
            title:'播放',
            content:'file/openAudioPage.action?' + url,
            shade: [0],
            area: ['440px', '120px'],
            offset: 'rb', /右下角弹出
        });
    } else if(fileType.indexOf("docum") >= 0){
        $.post("file/openFile.action", {
            "currentPath" : parentPath,
            "fileType" : fileType,
            "fileName" : fileName,
        }, function(data){
            layer.open({
                type: 1,
                area: ['720px', '570px'],
                title:false,
                scrollbar: false,
                content: '<textarea rows="50" cols="150">'+data+'</textarea>'
            });
        });
    } else if(fileType.indexOf("vido") >= 0){
        layer.open({
            type: 1,
            area: ['480px', '400px'],
            title:false,
            content: '<div id="a1"></div>'
        });
        var flashvars={
            f:'file/openFile.action?' + url,
            c:0,
            p:1,
            b:1
        };
        var params={bgcolor:'#FFF',allowFullScreen:true,allowScriptAccess:'always',wmode:'transparent'};
        CKobject.embedSWF('js/ckplayer/ckplayer.swf','a1','ckplayer_a1','480','400',flashvars,params);
        return false;
    }
    return false;
}

6. 在线播放视频

在线播放视频部分步骤类似于在线图片预览,但需借助ckplayer插件和flash播放器(需额外安装)。

1)在index.js中引入ckplayer插件,代码如下所示;

代码语言:javascript
复制
<script src="${pageContext.request.contextPath }/js/ckplayer/ckplayer.js"> </script>

2)前台index.js中请求file/openFile.action,代码后台同在线图片预览,此处省略代码。

3)前后获取到后台返回的视频地址后,则借助ckplayer播放当前视频,代码如下所示;

代码语言:javascript
复制
var params={bgcolor:'#FFF',allowFullScreen:true,allowScriptAccess:'always', wmode:'transparent'};  CKobject.embedSWF('js/ckplayer/ckplayer.swf','a1','ckplayer_a1','480','400',flashvars,params);

7. 在线播放音频

本系统在线播放音频无需播放插件,使用layUI弹出层播放即可。

1)确定是audio类型后,直接使用layer.open()方法弹出窗口,并打开file/openAudioPage.action返回的地址(index.js代码已在第1步给出);

2)在FileController类中添加openAudioPage()方法,将路径和文件名传入model,再返回给前台打开,即播放音乐。代码如下所示。

代码语言:javascript
复制
@RequestMapping("/openAudioPage")
public String openAudioPage(Model model, String currentPath, String fileName) {
    model.addAttribute("currentPath", currentPath);
    model.addAttribute("fileName", fileName);
    return "audio";
}
本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2020/07/19 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 1. 线预览或播放
  • 2. 在线预览图片和txt文档
  • 3. Office文档在线预览或播放
  • 4. 在线预览office文档
  • 5. 音视频线预览或播放
  • 6. 在线播放视频
  • 7. 在线播放音频
相关产品与服务
容器服务
腾讯云容器服务(Tencent Kubernetes Engine, TKE)基于原生 kubernetes 提供以容器为核心的、高度可扩展的高性能容器管理服务,覆盖 Serverless、边缘计算、分布式云等多种业务部署场景,业内首创单个集群兼容多种计算节点的容器资源管理模式。同时产品作为云原生 Finops 领先布道者,主导开源项目Crane,全面助力客户实现资源优化、成本控制。
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档