这里的设计是我们的主表要使用mybatis数据字典插件
数据字典是一种通用的程序设计方法。可以认为,不论什么程序,都是为了处理一定的主体,这里的主体可能是人员、商品(超子)、网页、接口、数据库表、甚至需求分析等等。当主体有很多的属性,每种属性有很多的取值,而且属性的数量和属性取值的数量是不断变化的,特别是当这些数量的变化很快时,就应该考虑引入数据字典的设计方法。
主表(需要上传文件的表)

文件表

pom文件添加集成数据字典
<!-- 用于集成数据字典 -->
<dependency>
<groupId>com.github.softwarevax</groupId>
<artifactId>dictionary-core</artifactId>
<version>0.0.2.RELEASE</version>
</dependency>
<dependency>
<groupId>com.github.softwarevax</groupId>
<artifactId>starter-dictionary-mybatis</artifactId>
<version>0.0.2.RELEASE</version>
</dependency>
字典配置
/**
* 集成数据字典功能
* @param dataSource
* @return
*/
@Bean
public DictionaryInterceptor dictionaryInterceptor(DataSource dataSource) {
// 数据字典 配置表
DatabaseTable config = new DatabaseTable();
String[] configColumn = new String[]{"item_name", "item_value", "item_type"};
String[] configCondition = new String[]{"1 = 1"};
String configTableName = "sys_data";
config.setColumn(configColumn);
config.setConditions(configCondition);
config.setTableName(configTableName);
DatabaseLoader dbLoader = new DatabaseLoader(dataSource);
dbLoader.addDictionaryTable(config);
DictionaryInterceptor interceptor = new DictionaryInterceptor(dbLoader);
return interceptor;
}
java bean
需要上传文件的表映射
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.extension.activerecord.Model;
import com.github.softwarevax.dict.core.Dictionary;
import com.github.softwarevax.dict.mybatis.starter.configuation.annoation.EnableDictionary;
import lombok.Data;
import lombok.EqualsAndHashCode;
/**
* <p>
*
* </p>
*
* @author Mr Wang
* @since 2022-01-21
*/
/开启数据字典功能
@EnableDictionary
@Data
@EqualsAndHashCode(callSuper = true)
public class PubTest extends Model {
private static final long serialVersionUID = 1L;
@TableId(value="id",type=IdType.ASSIGN_UUID)
private String id;
private String test;
/**
* table默认值,默认取加载的第一张表,property默认替换当前属性,column默认字典表的column为label, value默认字典表的value为value, conditions默认没有查询条件
* table:字典所在的表,可不配置,但性能会较低
* name:字典值value所在的列名
* value:字典键key所在的列名,字典没办法通过一个列确定时,可使用conditions再进行筛选,type为列名,habit_state为列的值, conditions内字符串格式为 key = value, 可含多个条件
* property:需要将替换后的字典,放到当前类的哪个属性中。默认是当前属性
*/
@Dictionary(table ="sys_data", column = "item_name", value = "item_value",conditions = {"item_type = 11"}, property = "updateUserName")
private String formKey;
@TableField(exist = false)
private String updateUserName;
}
添加页面上传文件部分代码
<input type="hidden" id='formKey' name="formKey"
th:value="${formKey}" class="layui-input"> <input
type="hidden" name="id" value="" class="layui-input">
<div class="layui-form-item" style="width: 300px">
<label class="layui-form-label required" style="width: 60px;">密级</label>
<div class="layui-input-block" style="margin-left: 90px;">
<!-- 表单中的密级只能使用这个字段 -->
<select name="secretDegree" id="secretDegree"
lay-filter="secretDegree" lay-verify="required"
lay-reqtext="密级不能为空"></select>
</div>
</div>
<!-- 附件上传的iframe id="file_1"用于区别一个表单中添加多个附件上传列表 -->
<div class="layui-form-item" style="height: 400px;">
<input id="fileFilter" type="hidden" value="">
<iframe id="file_1" src="public?mode=core/uploadfile/list"
frameborder="0" class="layadmin-iframe" name="iframeMain"
style="width: 100%; height: 100%;"></iframe>
</div>


上传文件java bean
import com.baomidou.mybatisplus.extension.activerecord.Model;
import com.github.dreamyoung.mprelation.JoinColumn;
import com.github.dreamyoung.mprelation.ManyToOne;
import java.time.LocalDateTime;
import java.util.Date;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableId;
import lombok.Data;
import lombok.EqualsAndHashCode;
/**
* <p>
* 附件表
* </p>
*
* @author Mr Wang
* @since 2022-02-15
*/
@Data
@EqualsAndHashCode(callSuper = true)
public class PubUploadFiles extends Model {
private static final long serialVersionUID = 1L;
/**
* ID
*/
@TableId(value = "FILE_ID", type = IdType.ASSIGN_UUID)
private String fileId;
/**
* 附件名称
*/
@TableField("FILE_NAME")
private String fileName;
/**
* 文件类别
*/
@TableField("FILE_TYPE")
private String fileType;
@TableField("FILE_SIZE")
private String fileSize;
/**
* 模块ID
*/
@TableField("PARENT_ID")
private String parentId;
/**
* 上传人
*/
@TableField("UPLOAD_BY")
private String uploadBy;
/**
* 上传时间
*/
@TableField("UPLOAD_TIME")
private Date uploadTime;
/**
* 文件密级
*/
@TableField("SECRET_DEGREE")
private String secretDegree;
//文件后缀
@TableField("FILE_EXT")
private String fileExt;
}
文件列表数据部分前端代码core/uploadfile/list.html
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<body th:fragment="content">
<div class="layuimini-container">
<input type="hidden" id="formKey"><input type="hidden"
id="fileType"><input type="hidden" id="fileFilter"> <input
type="hidden" id="maxSecret" name="maxSecret" value=0> <input
type="hidden" id="isSetAllSecret" name="isSetAllSecret" value=1>
<div class="layuimini-main">
<script type="text/html" id="toolbar">
<div class="layui-btn-container">
<button class="layui-btn layui-btn-normal layui-btn-sm data-add-btn" lay-event="add"> 添加附件 </button>
</div>
</script>
<table class="layui-table" id="currentTableId"
lay-filter="currentTableFilter"></table>
<script type="text/html" id="currentTableBar">
{{# if(d.secretDegree!=0&&d.secretDegree!=1&&d.secretDegree!=2&&d.secretDegree!=3){ }}
<a class="layui-btn layui-btn-normal layui-btn-xs data-count-edit" lay-event="setsecret">设定密级</a>
{{# } }}
<a class="layui-btn layui-btn-xs data-count-edit" lay-event="download">下载</a>
<a class="layui-btn layui-btn-xs layui-btn-danger data-count-delete" lay-event="delete">删除</a>
</script>
</div>
</div>
<script>
var forData;
layui
.use(
[ 'table' ],
function() {
var $ = layui.jquery, table = layui.table;
document.getElementById("fileFilter").value = parent.document
.getElementById("fileFilter").value;
var key = parent.document.getElementById("formKey");
alert(key);
var formSecret = parent.document
.getElementById("secretDegree");
var secret = 0;
//处理表单中不含密级字段或字段未选择时
if (formSecret != null && formSecret.value != "") {
secret = formSecret.value;
}
if (key == null) {
alert("表单未配置formKey。");
return false;
}
var fileKey = key.value;
var fileType = window.frameElement.id;
document.getElementById("formKey").value = fileKey;
document.getElementById("fileType").value = fileType;
table
.render({
skin : 'row', //行边框风格
even : true, //开启隔行背景
elem : '#currentTableId',
url : '/core/uploadfile/list?uid='
+ fileKey + '&fileType='
+ fileType + '&secret='
+ secret,
toolbar : '#toolbar',
defaultToolbar : [ 'filter', {
title : '提示:文件大小限制为1G',
layEvent : 'LAYTABLE_TIPS',
icon : 'layui-icon-tips'
} ],
cols : [ [
//{type: "checkbox", width:50, align: 'center'},
{
field : 'fileId',
width : '10%',
title : 'ID',
sort : true,
align : 'center'
},
{
field : 'fileName',
width : '25%',
title : '文件名',
align : 'left'
},
{
field : 'fileSize',
width : '13%',
title : '文件大小',
align : 'left'
},
{
field : 'uploadBy',
width : '10%',
title : '上传人',
align : 'left'
},
{
field : 'secretDegree',
width : '10%',
title : '密级',
align : 'center',
templet : function(record) {
if (record.secretDegree > document
.getElementById("maxSecret").value) {
document
.getElementById("maxSecret").value = record.secretDegree;
}
if (record.secretDegree == 0) {
return "公开";
} else if (record.secretDegree == 1) {
return "内部";
} else if (record.secretDegree == 2) {
return "秘密";
} else if (record.secretDegree == 3) {
return "机密";
} else {
document
.getElementById("isSetAllSecret").value = 0;
return "";
}
}
},
{
field : 'uploadTime',
width : '15%',
title : '上传时间',
align : 'left',
templet : "#formatTime"
},
{
title : '操作',
width : '25%',
toolbar : '#currentTableBar',
align : "center"
} ] ],
done : function() {
$("[data-field=fileId]").css(
'display', 'none');
},
page : false
});
/**
* toolbar监听事件
*/
table.on('toolbar(currentTableFilter)', function(
obj) {
if (obj.event === 'add') { // 监听添加操作
var index = layer.open({
title : '添加附件',
type : 2,
shade : 0.2,
maxmin : true,
shadeClose : true,
area : [ '700px', '300px' ],
content : './core/uploadfile/form.html'
});
$(window).on("resize", function() {
layer.full(index);
});
}
});
table
.on(
'tool(currentTableFilter)',
function(obj) {
formData = obj.data;
if (obj.event === 'delete') {
layer
.confirm(
'真的删除行么',
function(
index) {
obj
.del();
layer
.close(index);
$
.ajax({
url : '/core/uploadfile/delete',
method : 'post',
data : {
'id' : obj.data['fileId']
},
async : false,
success : function(
data) {
table
.reload(
'currentTableId',
{});
layer
.msg(
'删除成功',
{
icon : 1
});
},
error : function(
data) {
layer
.msg(
'删除失败',
{
icon : 2
});
}
});
});
} else if (obj.event === 'setsecret') {
var index = layer
.open({
title : '设定文件【'
+ obj.data['fileName']
+ '】的密级',
type : 2,
shade : 0.2,
maxmin : true,
shadeClose : true,
area : [
'480px',
'315px' ],
content : './public?mode=core/uploadfile/setSecret'
});
$(window)
.on(
"resize",
function() {
layer
.full(index);
});
} else if (obj.event === 'download') {
window
.open('/core/uploadfile/download?id='
+ obj.data['fileId']);
}
});
});
</script>
<script type="text/html" id="formatTime">
{{# if(d.uploadTime!=null){}}
<div>{{layui.util.toDateString(d.uploadTime, 'yyyy年MM月dd日 HH:mm:ss')}}</div>
{{# } }}
</script>
</body>
</html>
点击添加附件跳转页面代码/core/uploadfile/form.html
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>文件上传</title>
<link rel="stylesheet" th:href="@{/static/lib/layui-v2.6.3/css/layui.css}" media="all">
<link rel="stylesheet" th:href="@{/static/lib/jq-module/zyupload/zyupload-1.0.0.min.css}" media="all">
<link rel="stylesheet" th:href="@{/static/css/public.css}" media="all">
</head>
<body>
<div class="layuimini-container">
<div class="layuimini-main">
<div id="zyupload" class="zyupload"></div>
</div>
</div>
<script th:src="@{/static/lib/jquery-3.4.1/jquery-3.4.1.min.js}" charset="utf-8"></script>
<script th:src="@{/static/lib/layui-v2.6.3/layui.js}" charset="utf-8"></script>
<script th:src="@{/static/lib/jq-module/zyupload/zyupload-1.0.0.min.js}" charset="utf-8"></script>
<script type="text/javascript">
$(function () {
// 初始化插件
var fileKey=parent.document.getElementById("formKey").value;
var fileType=parent.document.getElementById("fileType").value;
var fileFilter=parent.document.getElementById("fileFilter").value;
var filter=[];
if(fileFilter!=null&&fileFilter!=""){
filter=fileFilter.split(',');
}else{
filter=["jpg", "png", "txt","docx","xls","et","xlsx","ppt","pps","pptx", "exe","wps","doc","zip","rar","jpeg"];
}
$("#zyupload").zyUpload({
width: "650px", // 宽度
height: "190px", // 宽度
itemWidth: "140px", // 文件项的宽度
itemHeight: "115px", // 文件项的高度
url: "/core/uploadfile/form?fileKey="+fileKey+"&fileType="+fileType, // 上传文件的路径
fileType: filter,// 上传文件的类型
fileSize: 1024*1024*1024, // 上传文件的大小
multiple: true, // 是否可以多个文件上传
dragDrop: false, // 是否可以拖动上传文件
tailor: true, // 是否可以裁剪图片
del: true, // 是否可以删除文件
finishDel: false, // 是否在上传文件完成后删除预览
/* 外部获得的回调接口 */
onSelect: function (selectFiles, allFiles) { // 选择文件的回调方法 selectFile:当前选中的文件 allFiles:还没上传的全部文件
//console.info("当前选择了以下文件:");
//console.info(selectFiles);
},
onDelete: function (file, files) { // 删除一个文件的回调方法 file:当前删除的文件 files:删除之后的文件
//console.info("当前删除了此文件:");
//console.info(file.name);
},
onSuccess: function (file, response) { // 文件上传成功的回调方法
// console.info("此文件上传成功:");
// console.info(file.name);
// console.info("此文件上传到服务器地址:");
//console.info(response);
$("#uploadInf").append("<p>" + response + "</p>");
},
onFailure: function (file, response) { // 文件上传失败的回调方法
//console.info("此文件上传失败:");
//console.info(file.name);
},
onComplete: function (response) { // 上传完成的回调方法
//console.info("文件上传完成");
// console.info(response);
parent.window.location.reload();
}
});
});
</script>
</body>
</html>

上传成功后设定密级页面core/uploadfile/setSecret
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<body th:fragment="content">
<div class="layuimini-container">
<div class="layuimini-main">
<div class="layui-form layui-form-pane" >
<div class="layui-form-item">
<div class="layui-inline">
<label class="layui-form-label required">文件密级</label>
<div class="layui-input-inline"><input type="hidden" id="fileId" name="fileId" lay-filter="fileId">
<select name="secretDegree" id="secretDegree" lay-filter="secretDegree" lay-verify="required"
lay-reqtext="密级不能为空"></select>
</div>
</div>
<div class="layui-inline">
<button type="submit" class="layui-btn layui-btn-primary" lay-submit lay-filter="saveBtn"> 保存</button>
</div>
</div>
</div>
</div>
</div>
<script th:inline="javascript">
layui.use(['form','layselect'], function () {
var form = layui.form,
layer = layui.layer,
layselectsecret = layui.layselect;
var sec=parent.parent.$("#secretDegree");
var degree=0;
if(sec.val()!=null&&sec.val()!=""){
degree=sec.val();
}
layselectsecret.render({
elem:"#secretDegree",
url:'/core/syssecretdegree/list?formDegree='+degree,//归属类型
format:function(data){
return{
code:data.secretDegree,
codeName:data.secretDegreeName
};
return data;
}
});
// 设置附件密级
document.getElementById('fileId').value=parent.formData['fileId'];
//监听提交
form.on('submit(saveBtn)', function (data) {
$('#saveBtn').attr('disabled',true);
$.ajax({
url:"/core/uploadfile/setsecret",
method:'post',
data: data.field,
async: true,
success: function (result) {
if(result.code==-1){
layer.msg(result.msg, {icon: 0});
return;
}
layer.msg('提交成功!',{
time: 500,
icon: 1
},
function(){
parent.window.location.reload();
parent.layer.close();
});
},
error:function (rsponse) {
layer.msg('出错了,错误信息:'+rsponse.msg, {icon: 2});
}
});
return false;
});
});
</script>
</body>
</html>

密级下拉框后端代码

//密级小于父页面密级
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.jincheng.bean.SysSecretDegree;
import com.jincheng.bean.SysUser;
import com.jincheng.service.ISysSecretDegreeService;
@RestController
public class SysSecretDegreeController {
@Autowired
private ISysSecretDegreeService service;
@RequestMapping("/core/syssecretdegree/list")
public List<SysSecretDegree> secretList(UsernamePasswordAuthenticationToken p,String formDegree){
SysUser user=(SysUser)p.getPrincipal();
QueryWrapper<SysSecretDegree> query=new QueryWrapper<SysSecretDegree>();
String degree="";
if(formDegree!=null&&formDegree!="") {
if(Integer.parseInt(formDegree)>Integer.parseInt(user.getSecretDegree())) {
degree=user.getSecretDegree();
}else {
degree=formDegree;
}
}else {
degree=user.getSecretDegree();
}
query.le("secret_degree",degree);
List<SysSecretDegree> list = service.list(query);
return list;
}
}
上传文件,设定密级,下载,删除等后端代码
import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.jincheng.bean.PubUploadFiles;
import com.jincheng.service.IPubUploadFilesService;
import com.jincheng.util.JsonResult;
import com.jincheng.util.SecretLabelAPI;
import com.jincheng.util.UtilTool;
import com.yunnan.bean.SecretLabelConfig;
/**
* <p>
* 附件表 前端控制器
* </p>
*
* @author Mr Wang
* @since 2022-02-15
*/
@Controller
public class PubUploadFilesController {
@Value("${savePath.uploadPath}")//配置文件配置
private String filePath;
@Autowired
private IPubUploadFilesService service;
@Autowired
private SecretLabelConfig config;
@GetMapping("/core/uploadfile/form.html")
public String showList() {
return "core/uploadfile/form.html";
}
/**
* 设定文件密级
* @param fileId
* @param secretDegree
* @param request
* @return
* @throws Exception
*/
@PostMapping("/core/uploadfile/setsecret")
public JsonResult setSecret(String fileId,String secretDegree,HttpServletRequest request) throws Exception {
PubUploadFiles upload=service.getById(fileId);
//加标//
SecretLabelAPI.enCode(config.secretUser, Integer.valueOf(secretDegree), filePath+"/"+fileId+upload.getFileExt(),config);
upload.setSecretDegree(secretDegree);
Boolean flg=upload.updateById();
if(flg) {
return JsonResult.success("保存成功。");
}else {
return JsonResult.error(-1, "保存失败。");
}
}
/**
* 文件下载
* @param id
* @param request
* @param response
* @throws Exception
*/
@ResponseBody
@GetMapping("/core/uploadfile/download")
public void download(String id,HttpServletRequest request,HttpServletResponse response) throws Exception {
PubUploadFiles upload=service.getById(id);
//File file=new File(filePath+"/"+id+upload.getFileExt());
解标///
String name=SecretLabelAPI.deCode(config.secretUser, filePath+"/"+id+upload.getFileExt(), 3,config);
File file=new File(name);
///
String fileName=upload.getFileName();
response.setContentType("text/html;charset=UTF-8");
response.setHeader("Content-disposition","attachment;filename="+fileName);
OutputStream os = response.getOutputStream();
FileInputStream fileInputStream = new FileInputStream(file);
DataInputStream dataInputStream = new DataInputStream(fileInputStream);
int r;
while((r=dataInputStream.read())!=-1) {
os.write(r);
}
System.out.println("已下载...");
fileInputStream.close();
dataInputStream.close();
///下载完后删除脱标文件/
file.delete();
}
/**
* 清除未设定密级的附件
* @param parentId
* @param request
*/
@PostMapping("/core/uploadfile/clear")
@ResponseBody
public void fileClear(String parentId,HttpServletRequest request) {
QueryWrapper<PubUploadFiles> queryWrapper = new QueryWrapper<PubUploadFiles>();
if (parentId != null && !parentId.isEmpty()) {
queryWrapper.eq("parent_id", parentId);
queryWrapper.isNull("secret_degree");
List<PubUploadFiles> list=service.list(queryWrapper);
list.forEach(item->{
File file=new File(filePath+"/"+item.getFileId()+item.getFileExt());
file.deleteOnExit();
});
service.remove(queryWrapper);
}
}
/**
* 删除附件
* @param id
* @param request
* @return
*/
@ResponseBody
@PostMapping("/core/uploadfile/delete")
public JsonResult delete(String id,HttpServletRequest request) {
PubUploadFiles upload=service.getById(id);
File file=new File(filePath+"/"+id+upload.getFileExt());
file.deleteOnExit();
Boolean flg =service.removeById(id);
if(flg) {
return JsonResult.success("删除成功。");
}else {
return JsonResult.error(-1, "删除失败。");
}
}
/**
* 打开附件列表
* @param fileType
* @param uid
* @param secret
* @param request
* @return
*/
@GetMapping("/core/uploadfile/list")
@ResponseBody
public JsonResult getList(String fileType,String uid,String secret,HttpServletRequest request) {
if (uid == null || uid.isEmpty()) {
return new JsonResult(0, "查看数据", null, 0);
}
QueryWrapper<PubUploadFiles> queryWrapper = new QueryWrapper<PubUploadFiles>();
if (fileType != null && !fileType.isEmpty()) {
queryWrapper.eq("file_type", fileType);
}
queryWrapper.and(i->i.le("secret_degree",secret).or().isNull("secret_degree"));
queryWrapper.eq("parent_id", uid);
List<PubUploadFiles> data = service.list(queryWrapper);
long count =data.size();
return new JsonResult(0, "查看数据", data, count);
}
/**
* 文件上传
* @param fileType
* @param fileKey
* @param request
* @return
* @throws Exception
*/
@PostMapping("/core/uploadfile/form")
@ResponseBody
public String uploadFile(@RequestParam("fileType") String fileType,@RequestParam("fileKey") String fileKey,HttpServletRequest request) throws Exception {
if(fileType==null||fileType.equals("")) {
fileType="1";
}
CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(request.getSession().getServletContext());
//判断 request 是否有文件上传,即多部分请求
if(multipartResolver.isMultipart(request)){
//转换成多部分request
MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request;
// 取得request中的所有文件名
Iterator<String> iter = multiRequest.getFileNames();
while(iter.hasNext()) {
MultipartFile mfile = multiRequest.getFile(iter.next());
String fileName=mfile.getOriginalFilename();
String filePostfix=fileName.substring(fileName.lastIndexOf("."));
String fileId=UtilTool.getUUid();//获取id
String saveName=fileId+filePostfix;
File saveFile = new File(filePath+"/"+saveName);
if(!saveFile.exists()){
saveFile.mkdirs();
}
mfile.transferTo(saveFile);
PubUploadFiles uploadFile=new PubUploadFiles();
判标///
Integer degree=SecretLabelAPI.GetSecretId(filePath+"/"+saveName,config);
if(degree!=-2) {
uploadFile.setSecretDegree(degree.toString());
}
///
uploadFile.setFileId(fileId);
uploadFile.setFileName(fileName);
uploadFile.setParentId(fileKey);
uploadFile.setFileType(fileType);
double size=mfile.getSize()/1024.0/1024;
String total=String.format("%.2f",size)+"MB";
uploadFile.setFileSize(total);
uploadFile.setFileExt(filePostfix);
uploadFile.setUploadTime(new Date());
uploadFile.setUploadBy(request.getRemoteUser());
uploadFile.insert();
}
}
return "上传成功。";
}
}
文件加标
import java.io.File;
import java.nio.file.Files;
import java.util.Random;
import com.eetrust.label.LabelOperator;
import com.eetrust.label.util.CharacterEnums;
import com.yunnan.bean.SecretLabelConfig;
public class SecretLabelAPI {
public static LabelOperator labelOperator;
public static String code;
/**
* 初始化,通过配置文件获取
* @throws Exception
*/
public static void initAPI(SecretLabelConfig config) throws Exception{
if(config.isAddLabel==0){
System.out.println("----------不加标,暂不需要初始化。-----------");
return;
}
labelOperator = new LabelOperator(config.serverIp,config.serverPort);
labelOperator.setCharacter(CharacterEnums.UTF_8);
}
/**
* 加标
* @param userId 用户全局唯一标识
* @param id OA密级ID
* @return 返回密标密级ID
* @throws Exception
*/
public static Integer enCode(String userId,Integer id,String fileName,SecretLabelConfig config) throws Exception{
if(labelOperator==null){
initAPI(config);
}
if(config.isAddLabel==0){
System.out.println("----------暂不加标-----------");
return -2;
}
File file=new File(fileName);
if(!file.exists()){
System.out.println("----------文件不存在。-----------");
return 0;
}
System.out.println("-------------path="+file.getAbsolutePath()+"--------");
int flg=labelOperator.isLabelledFile(file.getAbsolutePath());
System.out.println("-------------encode是否带标文件:"+flg+"--------");
if(flg!=0){
return flg;
}
return labelOperator.bindFileLabel(userId, fileName, CreateXml(id), (short) 0);
}
/**
*
* @param userId
* @param fileName
* @param state 客户端状态
* @return 复制文件后根据情况脱标
* @throws Exception
*/
public static String deCode(String userId,String fileName,Integer state,SecretLabelConfig config) throws Exception{
if(labelOperator==null){
initAPI(config);
}
File file=new File(fileName);
Random r=new Random();
String toFileName=file.getParent()+File.separator+"cp_"+r.nextInt(1000)+file.getName();
File toFile=new File(toFileName);
Files.copy(file.toPath(),toFile.toPath());
if(state==3){
System.out.println("+++++++++++++是否配置密标:"+config.isAddLabel+"+++++++++++++");
System.out.println("+++++++++++++userid:"+userId+"+++++++++++++");
System.out.println("+++++++++++++name:"+toFileName+"+++++++++++++");
if(config.isAddLabel!=0){
RemoveLabel(userId, toFileName,config);
}else{
System.out.println("-------------不做脱标--------");
}
}
return toFileName;
}
/**
* 获取文件密级ID指OA中的密级ID,-2表示明文。
* @param file
* @return OA密级ID
* @throws Exception
*/
public static Integer GetSecretId(String file,SecretLabelConfig config) throws Exception{
if(labelOperator==null){
initAPI(config);
}
if(config.isAddLabel==0){
System.out.println("-------------配置为不加标,不需要获取密级。--------");
return -2;
}
int flg=labelOperator.isLabelledFile(file);
System.out.println("-------------获取密标前,是否带标文件:"+flg+"--------");
if(flg==0){
return -2;
}else{
int a=labelOperator.getFileLevel(file);
System.out.println("-------------密级ID:"+a+"--------");
return CoverSecretIdToOA(a);
}
}
/**
* 加标文件则脱标
* @param userId
* @param file
* @throws Exception
*/
public static void RemoveLabel(String userId,String file,SecretLabelConfig config) throws Exception{
if(labelOperator==null){
initAPI(config);
}
if(config.isAddLabel==0){
System.out.println("-------------配置为不加标,不需要脱标操作。--------");
return;
}
if(!new File(file).exists()){
return;
}
int flg=labelOperator.isLabelledFile(file);
System.out.println("-------------脱标前,是否带标文件:"+flg+"--------");
if(flg!=0){
labelOperator.removeFileLabel(userId, file);
}
}
/**
* 生成密标xml
* @param secretId
* @return
*/
private static String CreateXml(Integer secretId){
String xml="<secAttrib><secrecy>"+CoverSecretId(secretId)+"</secrecy><status>2</status></secAttrib>";
return xml;
}
/**
* 将系统密级ID转换为密标的密级ID
* @param id
* @return
*/
private static Integer CoverSecretId(Integer id){
switch(id){
case -1:
case 0:
return 5;
case 1:
return 4;
case 2:
return 3;
case 3:
return 2;
case 4:
return 1;
default:
return 5;
}
}
/**
* -2表示明文
* @param id
* @return
*/
private static Integer CoverSecretIdToOA(Integer id){
switch(id){
case 0:
return -2;
case 1:
return 4;
case 2:
return 3;
case 3:
return 2;
case 4:
return 1;
case 5:
return 0;
default:
return 0;
}
}
/**
* 修改文件名,将密级写进文件名
* @param name
* @param secret
* @return
*/
public static String SetFileName(String name,String secret){
if(name.contains("【内部】")||name.contains("【公开】")||name.contains("【秘密】")||name.contains("【机密】")||name.contains("【绝密】")){
return name.replaceAll("【?(内部|公开|秘密|机密|绝密)】", secret);
}else{
return name+secret;
}
}
/**
* 将密级ID转换为密级,用于修改文件名。
* @param degree
* @return
*/
public static String CoverSecret(Integer degree){
String tmp="";
switch(degree){
case -1:
tmp="【公开】";
break;
case 1:
tmp="【内部】";
break;
case 2:
tmp="【秘密】";
break;
case 3:
tmp="【机密】";
break;
case 4:
tmp="【绝密】";
break;
default:
tmp="【内部】";
}
return tmp;
}
public static void main(String[] args) throws Exception {
}
}
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
@ConfigurationProperties
@Component
public class SecretLabelConfig{
@Value("${secretLabel.isAddLabel}")
public Integer isAddLabel;
@Value("${secretLabel.serverIp}")
public String serverIp;
@Value("${secretLabel.serverPort}")
public Integer serverPort;
@Value("${secretLabel.secretUser}")
public String secretUser;
}
配置文件
secretLabel:
isAddLabel: 0
serverIp: 192.168.1.222
serverPort: 8090
secretUser: qq
注:由于第一次实现这样的功能,单纯记录一下,可能存在很多问题,请谨慎参考。