基于springboot仿雀语的文档管理系统

项目介绍

本项目借鉴了雀语的一些UI设计,实现了文档在线管理的功能,知识库可以对不同分类的文档建立不同的库,知识库里面左边可以维护菜单菜单目录,右边实现在线预览。该项目可以防止用户下载和复制文档,只支持在线预览。

技术实现

文档上传的时候通过aspose把图片word和execel类型的文件转为pdf文件存储到nas,前端预览使用pdf.js加载预览pdf文档

项目预览

开发介绍

目录维护

左侧菜单点击加号可以维护目录

前端代码

<body class="white-bg">
    <div class="ibox-content">
        <form class="form-horizontal m-t" id="form1">
        <input id="id" name="id" type="hidden" />
        <input id="parentid" name="parentid" type="hidden" />
        <input id="deletemark" name="deletemark" type="hidden" />
        <input id="createdate" name="createdate" type="hidden" />
        <input id="createuserId" name="createuserId" type="hidden" />
        <input id="createusername" name="createusername" type="hidden" />
        <input id="modifydate" name="modifydate" type="hidden" />
        <input id="modifyuserid" name="modifyuserid" type="hidden" />
        <input id="modifyusername" name="modifyusername" type="hidden" />
        <div class="row">
            <div class="col-xs-12">
                <input type="text" id="name" class="form-control" placeholder="名称" />
            </div>
            <div class="col-xs-12">
                <textarea id="remark" class="form-control" placeholder="描述" style="width:100%;height:100px;"></textarea>
            </div>
            <div class="col-xs-12">
                <input type="text" id="sortcode" class="form-control" placeholder="序号" />
            </div>
            <div class="col-xs-12">
                <textarea id="keywords" class="form-control" placeholder="关键词" style="width:100%;height:100px;"></textarea>
            </div>
        </div>
        </form>
    </div>
</body>

后端代码

    @ApiOperation(value = "保存", notes = "")
    @PostMapping(value="/Save")
    public Result Save(@RequestBody String json) {
        DocmMenu model =  (DocmMenu) JSON.parseObject(json, DocmMenu.class);
        if(StrUtils.isBlank(model.getId())){
            model.setCreateuserid("admin");
            model.setDeletemark(new BigDecimal(0));
            model.setCreateusername("admin");
            model.setCreatedate(DateUtils.getNow());
            model.setId(UUID.randomUUID().toString());
            docmMenuService.add(model);
        }else {
            docmMenuService.update(model);
        }

        return Result.success(model,"成功!");
    }

文档维护

文档维护使用Dropzone实现前端文件上传,支持历史版本管理。

前端代码

<!DOCTYPE html>
<html>
<head>
    <title>文档管理</title>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="shortcut icon" href="favicon.ico">
    <link href="../css/bootstrap.min.css" rel="stylesheet">
    <link href="../css/font-awesome.min.css" rel="stylesheet">
    <link href="../css/plugins/jsTree/style.min.css" rel="stylesheet">
    <link href="../css/plugins/bootstrap-table/bootstrap-table.min.css" rel="stylesheet">
    <link href="../css/plugins/dropzone/dropzone.css" rel="stylesheet" type="text/css" />
    <!-- 全局js -->
    <script src="../js/jquery.min.js"></script>
    <script src="../js/bootstrap.min.js"></script>
    <script src="../js/plugins/jsTree/jstree.min.js"></script>
    <script src="../js/plugins/bootstrap-table/bootstrap-table.min.js"></script>
    <script src="../js/plugins/layer/layer.min.js"></script>
    <script src="../js/plugins/dropzone/dropzone.js"></script>
    <script src="../js/bd-framework.js"></script>

</head>
<body class="white-bg">
<div>
    <table id="table" style="width:100%"></table>
    <div id="main-container" style="margin-top: 10px;">
        <form action="/" class="dropzone" enctype="multipart/form-data" id="my-dropzone"
              method="post">
        </form>
        <textarea id="remark" class="form-control" placeholder="上传备注" style="width:100%;height:100px;"></textarea>
        <div>
            <!--上传按钮,提供多张图片一次性上传的功能-->
            <button id="submit-all" class="btn btn-outline btn-default" type="submit" >上传</button>
        </div>
    </div>

</div>
<script>
    var $table = $('#table');
    $(function () {
        getFileList();
    })

    function getFileList() {
        $table.html("");
        $.get("/api/Attachment/getList?businessid="+GetQuery('businessid'), {}, function (result, resultState) {
         if (result.code == 200) {

                if (result.data.length > 0) {
                    $table.append('<tr style="text-align: center; vertical-align: middle; border-style:solid; border-width:1px; ">'
                                            + '<td style="border-style:solid; border-width:1px;"><div style="padding:10px;width:30px;">序号</div></td>'
                                            + '<td style="border-style:solid; border-width:1px;"><div style="padding:10px;width:100px;">文件名称</div></td>'
                                            + '<td style="border-style:solid; border-width:1px;"><div style="padding:10px;width:80px;">上传人员</div></td>'
                                            + '<td style="border-style:solid; border-width:1px;"><div style="padding:10px;width:100px;">上传日期</div></td>'
                                            + '<td style="border-style:solid; border-width:1px;"><div style="padding:10px;width:200px;">备注</div></td>'
                                            + '<td style="border-style:solid; border-width:1px;"><div style="padding:10px;width:50px;">操作</div></td>'
                                    + '</tr>'
                                       );
                    for (var i = 0; i < result.data.length; i++) {
                        if (result.data[i].EXTENSION != "pdf" || (result.data[i].TMP_BUSINESSID || '') =='') {
                            $table.append('<tr style="border-style:solid; border-width:1px;">'
                                          + '<td style="border-style:solid; border-width:1px;text-align:center;">' + (i + 1) + '</td>'
                                           + '<td style="border-style:solid; border-width:1px;">'
                                               + '<a onclick="Download(\'' + result.data[i].ID + '\')" style="float: left" href="javascript:void(0)"><u>' + result.data[i].NAME + '</u></a>'
                                           + '</td>'
                                           + '<td style="border-style:solid; border-width:1px;">' + result.data[i].CREATEUSERNAME + '</td>'
                                           + '<td style="border-style:solid; border-width:1px;">' + result.data[i].CREATETIME + '</td>'
                                           + '<td style="border-style:solid; border-width:1px;">' + (result.data[i].REMARK || '') + '</td>'
                                           + '<td style="border-style:solid; border-width:1px;">'
                                               + '<div style="position:relative;padding:10px;">'
                                                   + '<button type="button" onclick="FileDelete(\'' + result.data[i].ID + '\')" data-id="' + result.data[i].ID + '">'
                                                         + '删除'
                                                   + '</button>'
                                               + '</div>'
                                           + '</td>'
                                       + '</tr>'
                                       );
                        }

                    }
                }
            }
        })
    }
    function FileDelete(Id) {
        var index = parent.layer.confirm('是否删除?', {
            btn: ['是', '否'] //按钮
        }, function () {
            $.get("/api/Attachment/deleteByPDF", { id: Id }, function (result, resultState) {
                    if (result.code == 200) {
                    parent.layer.msg("删除成功!");
                    getFileList();
                } else {
                    parent.layer.msg(result.message);
                    getFileList();
                }
            }, "json");
            parent.layer.close(index);
        }, function () {
            parent.layer.close(index);
        });
    }
    function Download(Id) {
        window.open('/api/Attachment/downFile?id=' + Id);
    };
</script>
<script>
    var loadIndex = null;
    //Dropzone的初始化,myDropzone为form的id
    Dropzone.options.myDropzone = {
        params: {
            businessid: GetQuery('businessid'),
            filePath: 'DocM'
            // 您可以在这里添加其他参数
        },
        //指定上传的路径
        url: "/api/Attachment/uploadFilesToPDF",
        maxFiles: 1, // 用于限制此Dropzone将处理的最大文件数
        maxFilesize: 100, // MB
        acceptedFiles: ".doc,.docx,.pdf,.PDF,.jpg,.JPG,.gif,.GIF,.png,.PNG,.bmp,.BMP", // 上传的类型
        dictDefaultMessage:
            '<div style="text-align: center; vertical-align: middle;padding-top:38px;"><span>将文件拖拽到此处</span>  \
			<span>(或点击上传)</span></div>'
          ,
        dictResponseError: 'Error while uploading file!',
        dictFileTooBig: "最大100M",
        //添加上传取消和删除预览的链接,默认不添加
        addRemoveLinks: true,
        //关闭自动上传功能,默认会true会自动上传
        //也就是添加一张图片向服务器发送一次请求
        autoProcessQueue: false,
        //允许上传多个
        uploadMultiple: false,
        //记得修改web.config 限制上传文件大小的节
        parallelUploads: 100,
        init: function () {
            var submitButton = document.querySelector("#submit-all")
            myDropzone = this; // closure

            //为上传按钮添加点击事件
            submitButton.addEventListener("click", function () {
                Dropzone.options.myDropzone.params.remark = $("#remark").val();
                loadIndex = parent.layer.load();
                //手动上传所有文件
                myDropzone.processQueue();
            });

            //当添加图片后的事件,上传按钮恢复可用
            this.on("addedfile", function () {
                $("#submit-all").removeAttr("disabled");
            });
            //当上传完成后的事件,接受的数据为JSON格式
            this.on("complete", function (data) {
                parent.layer.close(loadIndex);
                if (this.getUploadingFiles().length === 0 && this.getQueuedFiles().length === 0) {
                    var res = eval('(' + data.xhr.responseText + ')');
                    var msg;
                    if (res.code == 200) {
                        msg = "已成功上传!";
                        this.removeAllFiles();
                        getFileList()
                    }
                    else {
                        msg = "上传失败,失败的原因是:" + res.Message;
                    }
                    parent.layer.msg(msg);
                }
            });

            //删除文件的事件,当上传的文件为空时,使上传按钮不可用状态
            this.on("removedfile", function () {
                if (this.getAcceptedFiles().length === 0) {
                    $("#submit-all").attr("disabled", true);
                }
            });
        }
    };
</script>

</body>

后端代码

    @CrossOrigin
    @ApiOperation(value = "文件上传并且转为PDF", notes = "")
    @PostMapping("/uploadFileToPDF")
    public Result uploadFileToPDF(@RequestBody byte[] fileByte,
                             @RequestParam(value = "fileName",required = true) String fileName,
                             @RequestParam(value = "filePath",required = true) String filePath,
                             @RequestParam(value = "area",required = false) String area,
                             @RequestParam(value = "businessid",required = false) String businessid,
                             @RequestParam(value = "tmp_businessid",required = false) String tmp_businessid,
                             @RequestParam(value = "createUserId",required = false) String createUserId,
                             @RequestParam(value = "createUserName",required = false) String createUserName,
                             @RequestParam(value = "remark",required = false) String remark) {
        try {
            String uuid = UUID.randomUUID().toString();
            // 获取文件名
            String extension = getFileExtension(fileName);
            String newFileName = uuid + "." + extension;
            DocM_Attachment attachment = new DocM_Attachment();
            attachment.setBusinessid(businessid);

            attachment.setFilename(fileName);
            DateTimeFormatter fmt = DateTimeFormatter.ofPattern("yyMMdd");

            String uploadPath = filePath + FileConnect + LocalDate.now().format(fmt);
            attachment.setId(uuid);
            attachment.setCreateTime(DateUtils.getNow());
            attachment.setDirectory(uploadPath);
            attachment.setFilepath(uploadPath + FileConnect + newFileName);
            attachment.setFileSize(bytesToMegabytes((long)fileByte.length));
            attachment.setArea(area);
            attachment.setTmp_businessid(tmp_businessid);
            attachment.setExtension(extension);
            attachment.setCreateUserId(createUserId);
            attachment.setCreateUserName(createUserName);
            attachment.setRemark(remark);
            SmbFileUtils.save(fileByte,uploadPath,newFileName);

            InputStream inputStream = new ByteArrayInputStream(fileByte);
            OutputStream pdfStream = null;
            if(extension.equals("docx") || extension.equals("doc")){
                 pdfStream = doc2pdf(inputStream);
            }else if(extension.equals("png") || extension.equals("jpg") || extension.equals("gif")|| extension.equals("bmp")){
                 pdfStream = image2pdf(inputStream);
            }


            DocM_Attachment pdfAttachment = new DocM_Attachment();
            BeanUtils.copyProperties(attachment,pdfAttachment);
            pdfAttachment.setId(UUID.randomUUID().toString());
            String newPdfFileName = pdfAttachment.getId() + ".pdf";
            pdfAttachment.setFilepath(uploadPath + FileConnect + newPdfFileName);
            pdfAttachment.setArea("pdf");
            pdfAttachment.setTmp_businessid(attachment.getId());
            pdfAttachment.setFilename(fileName.split("\\.")[0] + ".pdf");
            pdfAttachment.setExtension("pdf");

            SmbFileUtils.save(toByteArray(pdfStream),uploadPath,newPdfFileName);

            inputStream.close();
            pdfStream.close();
            attachmentService.add(attachment);
            attachmentService.add(pdfAttachment);
            return Result.success(uuid,"成功!");
        } catch (Exception e) {
            e.printStackTrace();
            return Result.failed("文件上传失败");
        }
    }

知识库详情页面

左侧菜单使用JSTree.js插件,右侧文档预览使用pdf.js插件

前端代码

<!DOCTYPE html>
<html>
<head>
    <title>文档管理</title>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="shortcut icon" href="favicon.ico">
    <link href="../css/bootstrap.min.css" rel="stylesheet">
    <link href="../css/font-awesome.min.css" rel="stylesheet">
    <link href="../css/plugins/jsTree/style.min.css" rel="stylesheet">
    <link href="../css/plugins/bootstrap-table/bootstrap-table.min.css" rel="stylesheet">
    <!-- 全局js -->
    <script src="../js/jquery.min.js"></script>
    <script src="../js/bootstrap.min.js"></script>
    <script src="../js/plugins/jsTree/jstree.min.js"></script>
    <script src="../js/plugins/bootstrap-table/bootstrap-table.min.js"></script>
    <script src="../js/plugins/layer/layer.min.js"></script>
    <script src="../js/bd-framework.js"></script>
</head>
<body class="white-bg">
    <style>
    .pdf
    {
       position:relative;    
    }
    .main_container
    {
      display:flex;
    }
    .left_container
    {
        width:320px;   
        border-right:1px solid #e7e9e8; 
        overflow:scroll;
    }
    .right_contaner
    {
        flex:1;
    }
    #tree
    {
     
    }
    .jstree-anchor {
      font-size: 14px !important;
     /* color:#262626 !important;*/
    }
    .jstree-default .jstree-node {
        margin-top: 3px; /* 调整节点顶部的间距 */
        margin-bottom: 3px; /* 调整节点底部的间距 */
    }
    .btn-power
    {
        display:none;    
    }
    </style>
    <div class="main_container">
         <div class="left_container">
             <div id="directoryExpand">
             <input type="text" id="Keywords" class="form-control" placeholder="关键词搜索" />
                 <div style="display:flex; justify-content: space-between;align-items: center;margin-bottom:8px;padding:4px;">
                    <div onclick="directoryExpand()" style="font-size: 14px;color:#262626;padding-left:25px;"><i class="fa fa-bars" style="margin-right:12px;"  ></i>目录</div>
                    <div>
                        <div style="position: absolute;margin-left:-90px;margin-top:-12px;" class="btn-power">
                         <button data-toggle="dropdown" class="btn btn-outline btn-default dropdown-toggle" type="button" aria-expanded="false">
                              <i class="glyphicon glyphicon-plus" aria-hidden="true"></i>     
                        </button>
                         <button  onclick="btn_deleteAll()" class="btn btn-outline btn-default" type="button" >
                              <i class="glyphicon glyphicon-trash" aria-hidden="true"></i>     
                        </button>
                        <ul class="dropdown-menu pull-right">
                            <li>
                                <a href="javascript:;" onclick="btn_add()">新建分组</a>
                            </li>
                            <li>
                                <a href="javascript:;" onclick="btn_edit()">编辑分组</a>
                            </li>
                            <li>
                                <a href="javascript:;" onclick="btn_uploadFile()">上传文档</a>
                            </li>
                        </ul>
                        </div>
                    
                    </div>
                </div>
               
                <div id="tree"></div>
            </div>
            <div id="directoryNoExpand" style="display:none;">
                <div onclick="directoryNoExpand()" style="font-size: 14px;color:#262626;padding-left:12px;"><i class="fa fa-bars" ></i></div>
            </div>
         </div>
         <div class="right_contaner"  >
            <div class="pdf" >       
                <iframe  id="iframe1" width="100%" height="100%" src="" frameborder="0" ></iframe>
            </div>
         </div>
    </div>
    <script>
        var currentNode = null;
        var loadIndex = null;
        function directoryExpand() {
            $("#directoryExpand").hide();
            $(".left_container").css("width", "40px");
            $("#directoryNoExpand").show();   
        }
        function directoryNoExpand() {
            $("#directoryExpand").show();
            $(".left_container").css("width", "320px");
            $("#directoryNoExpand").hide();
        }
    
        $(function () {
            getPower();
           
            $(this).bind("contextmenu", function (e) {
                e.preventDefault();
            });
            $(".left_container").height($(window).height() - 7);
            $(".pdf").height($(window).height() - 7);
            document.getElementById('iframe1').onload = function () {
                parent.layer.close(loadIndex);
            }
            $("#Keywords").keydown(function (event) {
                initTree();
            });
        })
        var isManager = false;
        function getPower() {
            $.get("/api/DocManage/IsPowerMange", { id: GetQuery('Id') }, function (result, resultState) {
                if (result.code == 200) {
                    $(".btn-power").show();
                    isManager = true;
                }
                initTree();
            }, "json");
        }
        var $tree = $('#tree');
    
        function initTree() {
            if (!!GetQuery('Id')) {
                var postData = {}
                postData.id = GetQuery('Id');
                postData.keywords = $("#Keywords").val();
                $.get("/api/DocManage/GetTreeJson", postData, function (result, resultState) {
                    if (isManager) {
                        $tree
                        .on('activate_node.jstree', function (obj, e) {
                            var node = e.node;
                            if (node.id != undefined) {
                                currentNode = node;
                                loadPdf(node.id);
                            }
                        })
                        .jstree({
                            "multiple ": true,
                            'plugins': ["checkbox"],
                            'checkbox': {
                                'three_state': false,
                                'whole_node': false,
                                'tie_selection': false // 只有点击复选框才能勾选节点
                            },
                            'core': {
                                'data': result.data,
                                'check_callback': function (operation, node, node_parent, node_position, more) {
                                    // 允许所有操作,包括创建、重命名、删除、移动和复制节点
                                    return true;
                                }
                            }
                        })
                    } else {
                        $tree
                        .on('activate_node.jstree', function (obj, e) {
                            var node = e.node;
                            if (node.id != undefined) {
                                currentNode = node;
                                loadPdf(node.id);
                            }
                        })
                        .jstree({
                            "multiple ": true,
                            'core': {
                                'data': result.data
                            }
                        })
                    }
                }, "json");
            }
        }
        function loadPdf(businessid) {
            loadIndex = parent.layer.msg('文档加载中,请耐心等待!', { time: 1000 * 20 });
           
            $.get("/api/Attachment/getList?businessid="+businessid+"&area=pdf", {}, function (result, resultState) {
                if (result.code == 200) {
                    if (result.data.length > 0) {
                        for (var i = 0; i < result.data.length; i++) {
                            if (result.data[i].EXTENSION == "pdf") {
                                if (result.data[i].ID != currentNode.id) {
                                    $("#iframe1").attr("src", "../js/plugins/pdfjs-2.14.305-dist/web/DocManageViewer.html?file=" + "/api/Attachment/viewFile?id=" + result.data[i].ID);
                                }
                                break;
                            }
                        }
                    } else {
                        $("#iframe1").attr("src", "");
                        parent.layer.close(loadIndex);
                    }
                }
            }, "json");
        }
        function btn_add() {
            var viewData = {};
            if (currentNode) {
                viewData.parentid = currentNode.id;
            } else {
                viewData.parentid = GetQuery('Id')
            }
            var layerIndex = parent.layer.open({
                btn: ['确认'], //按钮
                yes: function (index, layero) {
                    var postData = parent.$("#layui-layer-iframe" + index)[0].contentWindow.GetWebControls("#form1");
                    $.ajax({
                        url: "/api/DocManage/Save",
                        type: "post",
                        contentType: 'application/json',
                        data: JSON.stringify(postData),
                        dataType: "json",
                        success: function (result) {
                            parent.layer.close(layerIndex);
                            // 在选中的节点下插入新节点
                            $tree.jstree('create_node', currentNode, { text: result.data.name, id: result.data.id, icon: "no-icon" }, 'last', function (newNode) {
                                //console.log('New node created with ID:', newNode.id);
                            });
                        }
                    });
                },
                type: 2,
                title: '新增',
                area: ['350px', '550px'],
                shadeClose: true, //开启遮罩关闭
                content: '/docManage/menuEdit.html',
                success: function (layero, index) {
                    parent.$("#layui-layer-iframe" + index)[0].contentWindow.SetWebControls(viewData);
                }
            });
        }
    
        function btn_edit() {
            var viewData = {};
            if (currentNode) {
                viewData.parentid = currentNode.id;
            } else {
                parent.layer.msg("请选择一个分组")
                return;
            }
            var layerIndex = parent.layer.open({
                btn: ['确认', '删除'], //按钮
                yes: function (index, layero) {
                    var postData = parent.$("#layui-layer-iframe" + index)[0].contentWindow.GetWebControls("#form1");
                    $.ajax({
                        url: "/api/DocManage/Save",
                        type: "post",
                        contentType: 'application/json',
                        data: JSON.stringify(postData),
                        dataType: "json",
                        success: function (result) {
                            parent.layer.close(layerIndex);
                            $tree.jstree('rename_node', currentNode, result.data.name);
                        }
                    });
                }, btn2: function (index, layero) {
                    var index = parent.layer.confirm('是否删除?', {
                        btn: ['是', '否'] //按钮
                    }, function () {
                        if (currentNode) {
                            var postData = {};
                            postData.id = currentNode.id;
                            $.get("/api/DocManage/Delete", postData, function (result, resultState) {
                                if (result.code == 200) {
                                    parent.layer.close(layerIndex);
                                    $tree.jstree('delete_node', currentNode);
                                }
                            }, "json");
                        }
                        parent.layer.close(index);
                    }, function () {
                        parent.layer.close(index);
                    });
                },
                type: 2,
                title: '编辑',
                area: ['350px', '550px'],
                shadeClose: true, //开启遮罩关闭
                content: '/docManage/menuEdit.html',
                success: function (layero, index) {
                    $.get("/api/DocManage/GetDetail", { id: currentNode.id }, function (result, resultState) {
                        parent.$("#layui-layer-iframe" + index)[0].contentWindow.SetWebControls(result.data);
                    }, "json");
    
                }
            });
        }
        function btn_deleteAll() {
            var index = parent.layer.confirm('是否删除?', {
                btn: ['是', '否'] //按钮
            }, function () {
                var postData = {};
                postData.ids = getTreeSelectedData().join(',');
                $.get("/api/DocManage/DeleteAll", postData, function (result, resultState) {
                    parent.layer.close(index);
                    $tree.jstree('delete_node', getTreeSelectedData());
                }, "json");
            }, function () {
                parent.layer.close(index);
            });
        }
        function btn_uploadFile() {
            var viewData = {};
            if (currentNode) {
                viewData.parentid = currentNode.id;
            } else {
                parent.layer.msg("请选择一个分组")
                return;
            }
            parent.layer.open({
                type: 2,
                title: '上传文档',
                area: ['850px', '750px'],
                shadeClose: true, //开启遮罩关闭
                content: '/docManage/uploadFileViewToPDF.html?businessid=' + currentNode.id,
                success: function (layero, index) {
                }
            });
        }
        function getTreeSelectedData() {
            var nodes = $tree.jstree("get_checked"); //使用get_checked方法
            return nodes;
        }
    </script>
    
</body>

文件转为pdf

使用aspose把文件转为pdf

    public OutputStream doc2pdf(InputStream inputStream) throws Exception {
        // 验证License 若不验证则转化出的pdf文档会有水印产生
        if (!getLicense()) {
            return null;
        }
        try {
            OutputStream outputStream =  new ByteArrayOutputStream();
            Document doc = new Document(inputStream);
            // 全面支持DOC, DOCX, OOXML, RTF HTML, OpenDocument, PDF, EPUB, XPS, SWF 相互转换
            doc.save(outputStream, SaveFormat.PDF);
            return  outputStream;
        } catch (Exception e) {
            e.printStackTrace();
            throw new Exception("word转pdf失败");
        }
    }

访问nas

使用jcifs-ng访问nas

导入包

<!-- samba共享文件夹-->
<dependency>
    <groupId>eu.agno3.jcifs</groupId>
    <artifactId>jcifs-ng</artifactId>
    <version>2.1.3</version>
</dependency>

工具栏

public class SmbFileUtils {
    static String ip = "";
    static String domain = "";
    static String userName = "";
    static String password = "";

    static void SmbFileUtils(){

    }
    //根据账号密码登录
    private static CIFSContext withNTLMCredentials(CIFSContext ctx) {
        return ctx.withCredentials(new NtlmPasswordAuthenticator(domain,
                userName, password));
    }

    //保存文件
    public static String save(byte[] byteArr, String url,String fileName) throws IOException {
        InputStream in = new ByteArrayInputStream(byteArr);
        String status = "";
        try {
            CIFSContext context = withNTLMCredentials(SingletonContext.getInstance());
            SmbFileWriter.createDirectory("smb://" + domain  +"/" + url, context);
            boolean result = SmbFileWriter.writeSmbFile(in, "smb://" + domain  +"/" + url +"/" + fileName, context);
            status = "success";
        } catch (Exception e) {
            e.printStackTrace();
            status = "error";
        } finally {
            in.close();
            return status;
        }
    }

    //获取文件
    public static  InputStream getFile(String filePath) throws IOException {
        String url = "smb://" + domain + "/" + filePath;

        try {
            CIFSContext context = withNTLMCredentials(SingletonContext.getInstance());
            SmbFileReader reader = new SmbFileReader();
            byte[] byteArr = reader.readSmbFile(url, context);
            InputStream input = new ByteArrayInputStream(byteArr);
            return  input;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
    //删除文件
    public static String delete(String filePath) throws IOException {
        String status = "";
        String url = "smb://" + domain + "/" + filePath;

        try {
            CIFSContext context = withNTLMCredentials(SingletonContext.getInstance());
            SmbFile file = new SmbFile(url, context);
            if (file.exists()) {
                file.delete();
                status = "success";
            }
        } catch (Exception e) {
            e.printStackTrace();
            status = "error";
        }
        return status;
    }
    //获取文件列表
    public static  List<HashMap> getPathList(String path) throws IOException {
        String url = "smb://" + domain + "/" + path;
        List<HashMap> filesList = new ArrayList<>();
        CIFSContext context = withNTLMCredentials(SingletonContext.getInstance());
        try {
            SmbFile smbFile = new SmbFile(url, context);
            SmbFile[] files = smbFile.listFiles();
            for (SmbFile file : files) {
                HashMap fileMap =new HashMap();
                fileMap.put("fileName",file.getName());
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); // 定义日期格式
                fileMap.put("date",sdf.format(new Date(file.getDate())));
                fileMap.put("size", String.format("%.2f", (file.length()/1024.0)/1024.0)+"MB");
                fileMap.put("fileType",file.isDirectory()?"文件夹":"文件");
                filesList.add(fileMap);
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
        return filesList;
    }

    static class SmbFileReader {
        public byte[] readSmbFile(String path, CIFSContext context) throws IOException {
            try  {
                SmbFile smbFile = new SmbFile(path, context);
                long fileSize = smbFile.length();
                if (fileSize > Integer.MAX_VALUE) {
                    System.out.println("file too big...");
                    return null;
                }
                InputStream fi = smbFile.getInputStream();
                byte[] buffer = new byte[(int) fileSize];
                int offset = 0;
                int numRead = 0;
                while (offset < buffer.length
                        && (numRead = fi.read(buffer, offset, buffer.length - offset)) >= 0) {
                    offset += numRead;
                }
                // 确保所有数据均被读取
                if (offset != buffer.length) {
                    throw new IOException("Could not completely read file "
                            + smbFile.getName());
                }
                fi.close();
                return buffer;
            } catch (Exception e) {
                e.printStackTrace();
            }
            return null;
        }
    }

    static class SmbFileWriter {
        static boolean writeSmbFile(String source, String target, CIFSContext context) throws IOException {
            if (StrUtils.isEmpty(source) || StrUtils.isEmpty(target)) {
                return false;
            }
            return writeSmbFile(Files.newInputStream(Paths.get(source)),
                    target, context);
        }

        static boolean writeSmbFile(InputStream in, String target, CIFSContext context) throws IOException {
            if (Objects.nonNull(in) && StrUtils.isNotEmpty(target)) {
                try (SmbFile file = new SmbFile(target, context)) {
                    try (SmbFile parent = new SmbFile(file.getParent(), context)) {
                        if (!parent.exists()) {
                            createDirectory(file.getParent(), context);
                        }
                        if (!file.exists()) {
                            file.createNewFile();
                        }
                    }
                    try (OutputStream os = file.getOutputStream()) {
                        byte[] bytes = new byte[1024];
                        while (in.read(bytes) != -1) {
                            os.write(bytes);
                        }
                        return true;
                    }
                }finally {
                    in.close();
                }
            }
            return false;
        }

        static SmbFile createDirectory(String targetDir, CIFSContext context) throws MalformedURLException,
                CIFSException, MalformedURLException {
            try (SmbFile dir = new SmbFile(targetDir, context)) {
                if (!dir.exists()) {
                    dir.mkdir();
                }
                return dir;
            }
        }
    }
}

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:/a/540461.html

如若内容造成侵权/违法违规/事实不符,请联系我们进行投诉反馈qq邮箱809451989@qq.com,一经查实,立即删除!

相关文章

Excel从零基础到高手【办公】

第1课 - 快速制作目录【上篇】第1课 - 快速制作目录【下篇】第2课 - 快速定位到工作表的天涯海角第3课 - 如何最大化显示工作表的界面第4课 - 给你的表格做个瘦身第5课 - 快速定位目标区域所在位置第6课 - 快速批量填充序号第7课 - 按自定义的序列排序第8课 - 快速删除空白行第…

接招吧! selenium环境+元素定位大法

selenium 与 webdriver Selenium 是一个用于 Web 测试的工具&#xff0c;测试运行在浏览器中&#xff0c;就像真正的用户在手工操作一样。支持所有主流浏览器 WebDriver 就是对浏览器提供的原生API进行封装&#xff0c;使其成为一套更加面向对象的Selenium WebDriver API。 …

UltraScale 架构 SelectIO 资源之IODELAY与IOSERDES仿真与使用

平台&#xff1a;vivado2018.3 具体内容见ug571-ultrascale-selectio IDELAYE3 在调试超高速信号的时候&#xff0c;需要使用iodelayiserdes来调试校准输入信号。例如外部某ADC采样率为5GHZ&#xff0c;外部ADC使用2.5GHZ的时钟去采集输入信号。为了实现采集&#xff0c;adc芯…

普乐蛙VR航天体验馆设备VR太空飞船VR元宇宙展厅

三天小长假就要来啦&#xff01;五一假期也即将到来。老板们想捉住人流量这个财富密码吗&#xff1f;那快快行动起来&#xff01;开启VR体验项目&#xff0c;假期赚翻天&#xff01;小编亲测&#xff01;&#xff01;这款设备刺激好玩&#xff0c;想必会吸引各位家长小孩、学生…

Normalization

Norm介绍 归一化层&#xff0c;目前主要有这几个方法&#xff0c;Batch Normalization&#xff08;2015年&#xff09;、Layer Normalization&#xff08;2016年&#xff09;、Instance Normalization&#xff08;2017年&#xff09;、Group Normalization&#xff08;2018年&…

【研发日记】CANoe自动化测试的配置方式(三)——SystemVariables数组方式

文章目录 前言 一、例程功能 二、仿真ECU 三、SystemVariables数组&#xff1a; 四、测试模块 五、测试运行效果 六、分析和应用 总结 前言 近期在做的一个自动化测试项目&#xff0c;尝试了一种以前没用过的测试配置方式&#xff0c;感觉效果还不错。然后又回顾了一下以…

php其他反序列化知识学习

简单总结一下最近学习的&#xff0c;php其他的一些反序列化知识 phar soap session 其他 __wakeup绕过gc绕过异常非公有属性&#xff0c;类名大小写不敏感正则匹配&#xff0c;十六进制绕过关键字检测原生类的利用 phar 基础知识 在 之前学习的反序列化利用中&#xff0…

Golang | Leetcode Golang题解之第19题删除链表的倒数第N个结点

题目&#xff1a; 题解&#xff1a; func removeNthFromEnd(head *ListNode, n int) *ListNode {dummy : &ListNode{0, head}first, second : head, dummyfor i : 0; i < n; i {first first.Next}for ; first ! nil; first first.Next {second second.Next}second.N…

谷歌推出适用于安卓设备的“Find My Device”网络,功能类似苹果Find My

谷歌今日推出了适用于安卓设备的“Find My Device”网络&#xff0c;其功能类似于苹果的“Find My”网络&#xff0c;旨在帮助用户定位丢失、被盗的安卓产品。 安卓的“Find My Device”网络可以利用数以亿计运行 Android 9 或更高版本的安卓设备&#xff0c;通过蓝牙信号追踪丢…

Golang ProtoBuf 初学者完整教程:语法

一、编码规范推荐 1、文件名使用小写下划线的命名风格&#xff0c;例如 lower_snake_case.proto 2、使用 2 个空格缩进 3、包名应该和目录结构对应 4、消息名使用首字母大写驼峰风格(CamelCase)&#xff0c;例如message StudentRequest { ... } 5、字段名使用小写下划线的风格…

内网通如何去除广告,内网通免广告生成器

公司使用内网通内部传输确实方便&#xff01;但是会有广告弹窗推送&#xff01;这个很烦恼&#xff01;那么如何去除广告呢&#xff01; 下载&#xff1a; 链接&#xff1a;https://pan.baidu.com/s/1CVVdWexliF3tBaFgN1W9aw?pwdhk7m 提取码&#xff1a;hk7m ID&#xff1a;…

数据结构之来链表——单链表

什么是单链表&#xff1a; 文字说明&#xff1a; 单链表顾名思义&#xff0c;就是指单项链表&#xff0c;即只有一个方向的链性线性表。 图解&#xff1a; 如下图所示&#xff0c;即为链表&#xff08;DATA为我们自己所定义的数据类型&#xff09;&#xff1a; 单链表的创建&am…

酷柚易讯无人共享空间单开版安装说明

1、安装环境准备 PHP环境7.4 mysql数据库需要5.7 同时需要安装宝塔面板&#xff08;&#xff57;&#xff57;&#xff57;&#xff0e;&#xff42;&#xff54;&#xff0e;&#xff43;&#xff4e;&#xff09; &#xff12;、获取系统安装包 联系工作人员获取安装包后…

面试:线程和线程池

目录 目标 一、线程有哪些状态 1、新建态&#xff08;NEW&#xff09;&#xff1a; 2、可运行态&#xff08;RUNNABLE&#xff09;&#xff1a; 3、终结态&#xff08;TERMINATED&#xff09;&#xff1a; 4、阻塞态&#xff08;BLOCKED&#xff09;&#xff1a; 5、等待态…

springboot3使用自定义注解+AOP+redis优雅实现防重复提交

⛰️个人主页: 蒾酒 &#x1f525;系列专栏&#xff1a;《spring boot实战》 &#x1f30a;山高路远&#xff0c;行路漫漫&#xff0c;终有归途 目录 写在前面 实现思路 实现步骤 1.定义防重复提交注解 2.编写一个切面去发现该注解然后执行防重复提交逻辑 3.测试 …

VNC Viewer 连接远程主机及常见错误处理(The connection closed unexpectedly)

搭建可接收vnc连接的环境 1、下载镜像 https://github.com/fcwu/docker-ubuntu-vnc-desktop 该镜像是含有ubuntu 通过docker运行的桌面环境&#xff0c;并接受vnc 的连接 docker pull dorowu/ubuntu-desktop-lxde-vnc 2、运行容器 1&#xff09;只暴露容器的80端口&#…

1.汉诺塔问题

C力扣 汉诺塔 class Solution { public:void hanota(vector<int>& a, vector<int>& b, vector<int>& c) {dfs(a,b,c,a.size());}void dfs(vector<int>& a, vector<int>& b, vector<int>& c,int n){if(n1){c.push…

李廉洋;4.13黄金,原油最新资讯,下周一盘走势分析及策略。

美国杜克大学大宗商品研究教授Harvey表示&#xff0c;目前除了避险情绪外&#xff0c;“上涨惯性”也是促使黄金“疯涨”的原因。他表示&#xff1a;“目前不断涌入黄金市场的资金实际上在增加风险敞口&#xff0c;除了散户&#xff0c;对冲基金和其他机构投资者也加入了黄金热…

股票价格预测 | Python使用LSTM预测股票价格

文章目录 效果一览文章概述代码设计效果一览 文章概述 Python使用LSTM预测股票价格 代码设计 import pandas as pd import matplotlib.pyplot as plt import numpy as np import tensorflowfrom numpy import

【Jenkins】Jenkins自动化工具介绍

目录 技术背景常规的手动打包步骤 Jenkins简介起源与发展Jenkins的核心价值1.自动化1.1代码构建1.2测试自动化1.3自动部署 2.持续集成与持续部署CI/CD的概念如何减少集成问题更快速地发布软件版本 Jenkins优势Jenkins的主要竞争对手Travis CI:CircleCI:GitLab CI: Jenkins与其他…