目录
Java后台集成mybatis-plus
1、添加依赖
2、修改配置文件application.yml或application.properties
3、resources下添加mybatis-config文件,路径需要和mybatis plus配置文件中的configLocation的路径一致
4、添加MybatisPlusConfig类
java后台实现文件上传代码
添加一个文件上传实体类Wdzl
添加mapper
添加service
添加controller
前端页面代码
HTML部分
js部分
成果展示
Java后台集成mybatis-plus
1、添加依赖
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.4.2</version>
</dependency>
2、修改配置文件application.yml或application.properties
mybatis-plus:
# 搜索指定包别名
typeAliasesPackage: com.xxx.**.domain
# 配置mapper的扫描,找到所有的mapper.xml映射文件
mapperLocations: classpath*:mybatis/mapper/**/*Mapper.xml
# 指定Mapper XML文件的位置,使用classpath通配符指定路径。
#mapper-locations: classpath*:/mapper/**/*.xml
# 指定实体类的包路径,用于自动扫描并注册类型别名。
#type-aliases-package: com.xxx.*.domian
configLocation: classpath:mybatis/mybatis-conf.xml
# 全局配置
global-config:
db-config:
#id-type: ID_WORKER # 主键ID的生成策略,可选值包括:AUTO、NONE、INPUT、ID_WORKER、UUID
id-type: AUTO
#机器 ID 部分(影响雪花ID)
workerId: 1
#数据标识 ID 部分(影响雪花ID)(workerId 和 datacenterId 一起配置才能重新初始化 Sequence)
datacenterId: 18
# 字段验证策略,可选值包括:not_null、not_empty、default
field-strategy: not_empty
#驼峰下划线转换(将数据库字段的下划线命名规则转换为 Java 实体类属性的驼峰命名规则)
db-column-underline: true
#刷新mapper 调试神器
refresh-mapper: true #refresh-mapper在生产环境中应该设置为false,以避免不必要的性能开销
#数据库大写下划线转换
#capital-mode: true
#序列接口实现类配置
#key-generator: com.baomidou.springboot.xxx
#逻辑删除配置(下面3个配置)
logic-delete-field: deleted # 逻辑删除字段名
logic-delete-value: 1 # 逻辑删除字段的值表示已删除
logic-not-delete-value: 0 # 逻辑删除字段的值表示未删除
#自定义SQL注入器
#sql-injector: com.baomidou.mybatisplus.mapper.LogicSqlInjector
#自定义填充策略接口实现
#meta-object-handler: com.baomidou.springboot.xxx
configuration:
# 将 Java 实体类属性的驼峰命名规则转换为数据库字段的下划线命名规则
map-underscore-to-camel-case: true
# 是否开启二级缓存。
cache-enabled: false
# 这个配置会将执行的sql打印出来,在开发或测试的时候可以用
log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
3、resources下添加mybatis-config文件,路径需要和mybatis plus配置文件中的configLocation的路径一致
4、添加MybatisPlusConfig类
@EnableTransactionManagement(proxyTargetClass = true)@Configuration
public class MybatisPlusConfig
{
@Bean
public MybatisPlusInterceptor mybatisPlusInterceptor()
{
MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
// 分页插件
interceptor.addInnerInterceptor(paginationInnerInterceptor());
// 乐观锁插件
interceptor.addInnerInterceptor(optimisticLockerInnerInterceptor());
// 阻断插件
interceptor.addInnerInterceptor(blockAttackInnerInterceptor());
return interceptor;
}
/**
* 分页插件,自动识别数据库类型 https://baomidou.com/guide/interceptor-pagination.html
*/
public PaginationInnerInterceptor paginationInnerInterceptor()
{
PaginationInnerInterceptor paginationInnerInterceptor = new PaginationInnerInterceptor();
// 设置数据库类型为mysql
paginationInnerInterceptor.setDbType(DbType.MYSQL);
// 设置最大单页限制数量,默认 500 条,-1 不受限制
paginationInnerInterceptor.setMaxLimit(-1L);
return paginationInnerInterceptor;
}
/**
* 乐观锁插件 https://baomidou.com/guide/interceptor-optimistic-locker.html
*/
public OptimisticLockerInnerInterceptor optimisticLockerInnerInterceptor()
{
return new OptimisticLockerInnerInterceptor();
}
/**
* 如果是对全表的删除或更新操作,就会终止该操作 https://baomidou.com/guide/interceptor-block-attack.html
*/
public BlockAttackInnerInterceptor blockAttackInnerInterceptor()
{
return new BlockAttackInnerInterceptor();
}
}
java后台实现文件上传代码
添加一个文件上传实体类Wdzl
@Datapublic class WdzL {
private String uploadIndex;//上传文件索引
private String id;
private String dxId;
private String mc;
private String lj;
private String scrId;
private String scr_name;
@JsonFormat(pattern="yyyy-MM-dd HH:mm",timezone="GMT+8") //返回时间格式
private Date scsj;
private String wdlx;
private String wdlx_name;
private String bz;
public WdzL(String uploadIndex,String id, String dxId, String mc, String lj, String scrId,Date scsj,String bz,String wdlx) {
super();
this.uploadIndex = uploadIndex;
this.id = id;
this.dxId = dxId;
this.mc = mc;
this.lj = lj;
this.scrId = scrId;
this.scsj = scsj;
this.wdlx = wdlx;
this.bz = bz;
}
}
添加mapper
@Repositorypublic interface WdzlMapper extends BaseMapper<WdzL> {
List<WdzL> getWdzlBydxId(@Param("dxId") String dxId);
void insertWdzl(@Param("wdzl") WdzL wdzL);
}
添加service
@Servicepublic class WdzlService{
@Resource
WdzlMapper wdzlMapper;
public JSONObject insertWdzl(String fileList, String dxId, String scrId, String fileDir, String dirName,
MultipartFile[] uploadFiles) throws Exception {
JSONObject result = new JSONObject();
result.put("code", "error");
System.out.println("--------------dxId--------------:" + dxId);
if (fileList == null || "".equals(fileList)) {
result.put("msg", "内容不可为空");
return result;
}
if (uploadFiles == null || uploadFiles.length == 0) {
result.put("msg", "请先上传文件");
return result;
}
JSONObject object = JSON.parseObject(fileList);
if (object == null || object.size() == 0) {
result.put("msg", "内容不可为空");
return result;
}
if (uploadFiles.length != object.size()) {
result.put("msg", "表格条数与文件不匹配");
return result;
}
String name = "";
List<WdzL> wdzLs = wdzlMapper.getWdzlBydxId(dxId);
int size = object.size();
Date scsj = new Date();
ArrayList<WdzL> list = new ArrayList<WdzL>();
for (int i = 0; i < size; i++) {
JSONObject jsonOb = object.getJSONObject(i + "");
String uploadIndex = jsonOb.getString("uploadIndex");
String wjmc = jsonOb.getString("wdmc");
String dalx = jsonOb.getString("wdlx");
String bz = jsonOb.getString("bz");
list.add(new WdzL(uploadIndex, UUID.randomUUID().toString(), dxId, wjmc, "", scrId, scsj, bz, dalx));
}
if(!wdzLs.isEmpty() && !list.isEmpty()){
for(WdzL a:wdzLs){
for(WdzL b:list){
if(a.getMc().equals(b.getMc())){
name += "【"+a.getMc()+"】";
}
}
}
if(!"".equals(name)) {
result.put("msg", "库中存在相同文件,重复文件名:"+name);
return result;
}
}
// 文件上传
String classes_path = ClassUtils.getDefaultClassLoader().getResource("").getPath();
classes_path = URLDecoder.decode(classes_path, "utf-8");
File eclipsePath = new File(classes_path + File.separator + "static");
if(!eclipsePath.exists()) {
eclipsePath.mkdirs();
}
String rootPath = eclipsePath.getPath();
/* String filePath = "业务"+ File.separator + dxId + File.separator + "文档资料"; */
String filePath = fileDir + File.separator + dxId + File.separator + dirName;
File directory = new File(rootPath + File.separator + filePath);
if (!directory.exists()) {
directory.mkdirs();
}
for (int j = 0; j < uploadFiles.length; j++) {
MultipartFile file = uploadFiles[j];
if (file != null && !file.isEmpty()) {
WdzL wdzl = list.get(j);
String wjmc = wdzl.getMc();// 用户填写的文件名称
String originalName = file.getOriginalFilename();// 文件原始名称
String filename = originalName;
if (wjmc != null && !"".equals(wjmc)) {
// 如果两者名称不相同
if (!originalName.equals(wjmc)) {
String originalNameSuffix = originalName.substring(originalName.lastIndexOf(".")).toLowerCase();// 获取后缀
String wjmcPrefix = wjmc.substring(0, wjmc.lastIndexOf("."));// 获取前缀
filename = wjmcPrefix + originalNameSuffix;
wdzl.setMc(filename);
}
}
File newfile = new File(rootPath + File.separator + filePath + File.separator + filename);
file.transferTo(newfile); // 上传源
wdzl.setLj("/" + fileDir + "/" + dxId + "/"
+ dirName + "/" + filename);
wdzlMapper.insertWdzl(wdzl);
result.put("code", "ok");
} else {
result.put("msg", "存在大小是0kb的文件,不支持上传0kb的文件");
return result;
}
}
return result;
}
}
添加controller
@RestController@RequestMapping("wdzl")
public class WdzlController {
@Autowired
WdzlService wdzlService;
@RequestMapping("insertWdzl")
public JSONObject insertWdzl(String fileList, String dxId, String scrId, String fileDir, String dirName,
@RequestParam(value="uploadFiles",required=false) MultipartFile[] uploadFiles) throws Exception{
return wdzlService.insertWdzl(fileList, dxId, scrId,fileDir,dirName, uploadFiles);
}
}
前端页面代码
HTML部分
<!DOCTYPE html><html>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width,initial-scale=1,user-scalable=0">
<title>洪福湿地</title>
<!-- 引入 WeUI CDN 链接 -->
<link rel="stylesheet" href="./plugin/weui-2.6.4/dist/style/weui.min.css"/>
<link rel="stylesheet" href="./css/weui.css"/>
<link rel="stylesheet" href="./css/weuix.css"/>
<style>
</style>
</head>
<body ontouchstart>
<div class="page-bd-15">
<div class="weui-form">
<div class="weui-form__bd">
<div class="weui-form__text-area">
<h2 class="weui-form__title">XXXXX问题反馈表</h2>
</div>
<div class="weui-form__control-area">
<div class="weui-cells__group weui-cells__group_form">
<div class="weui-cells__title">个人基本信息</div>
<div class="weui-cells">
<label for="js_input1" class="weui-cell weui-cell_active">
<div class="weui-cell__hd"><span class="weui-label">微信号</span></div>
<div class="weui-cell__bd">
<input id="js_input1" class="weui-input" placeholder="填写本人微信号" />
</div>
</label>
<label for="js_input2" class="weui-cell weui-cell_active">
<div class="weui-cell__hd"><span class="weui-label">昵称</span></div>
<div class="weui-cell__bd">
<input id="js_input2" class="weui-input" placeholder="填写本人微信号的昵称"/>
</div>
</label>
<label for="js_input3" class="weui-cell weui-cell_active">
<div class="weui-cell__hd"><span class="weui-label">联系方式</span></div>
<div class="weui-cell__bd">
<input id="js_input3" class="weui-input" placeholder="请填写联系方式" type="number" pattern="[0-9]*" />
</div>
</label>
<div class="weui-cells weui-cells_form">
<div class="weui-cells__title" style="margin-top: 8px">问题描述</div>
<div class="weui-cell weui-cell_active">
<div class="weui-cell__bd">
<textarea class="weui-textarea" placeholder="请描述你的问题" rows="3" maxlength="200"></textarea>
<div role="option" aria-live="polite" class="weui-textarea-counter"><span>0</span>/200</div>
</div>
</div>
</div>
<div class="weui-cell weui-cell_active">
<div class="weui-uploader">
<div class="weui-uploader__hd">
<p class="weui-uploader__title">图片上传及预览</p>
<div class="weui-uploader__info"><span class="imgSum"></span>/8</div>
</div>
<div class="weui-uploader__bd">
<ul class="weui-uploader__files" id="uploaderFiles">
</ul>
<div class="weui-uploader__input-box">
<input id="uploaderInput" class="weui-uploader__input" accept="image/*" multiple="" type="file">
</div>
</div>
</div>
<div class="weui-gallery" style="display: none">
<span class="weui-gallery__img"></span>
<div class="weui-gallery__opr">
<a href="javascript:" class="weui-gallery__del">
<i class="weui-icon-delete weui-icon_gallery-delete"></i>
</a>
</div>
</div>
</div>
<div class="weui-cell weui-cell_active">
<div class="weui-uploader">
<div class="weui-uploader__hd">
<p class="weui-uploader__title">视频上传</p>
</div>
<div class="weui-uploader__bd">
<ul class="weui-uploader__files" id="uploaderFiles_videoList">
</ul>
<div class="weui-uploader__input-box">
<input id="uploaderFiles_video" class="weui-uploader__input" accept="video/*" multiple="" type="file">
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<div class="weui-form__ft">
<div class="weui-form__opr-area">
<a role="button" disabled aria-disabled="true" class="weui-btn weui-btn_primary weui-btn_disabled" οnclick="submitTable()" href="javascript:">确定</a>
</div>
<div class="weui-form__extra-area">
<div class="weui-footer">
<p class="weui-footer__links">
<a href="./pay.html" class="weui-footer__link">XXXX门户网站</a>
</p>
<p class="weui-footer__text">Copyright © 2023 XXXXXX技术有限公司 版权所有 </p>
</div>
</div>
</div>
</div>
<div role="alert" id="js_toast" style="display: none;">
<div class="weui-mask_transparent"></div>
<div class="weui-toast">
<i class="weui-icon-success-no-circle weui-icon_toast"></i>
<p class="weui-toast__content">已完成</p>
</div>
</div>
</div>
<!--页面切换-->
<script src="http://res.wx.qq.com/open/js/jweixin-1.6.0.js"> </script>
<script src="./js/zepto.min.js"></script>
<script src="./js/zepto.weui.js"></script>
<script src="./js/lrz.min.js"></script>
<script src="https://res.wx.qq.com/t/wx_fed/weui.js/res/1.2.18/weui.min.js"></script>
<script src="js/common.js"></script>
<!--<script src="js/main.js"></script>-->
</body>
</html>
js部分
<script>
$(function(){
uploaderImg();
uoloaderVideo();
sumImgSize();
});
var uploadFiles = [];//存放上传时选择的文件
function sumImgSize() {
var length = document.getElementById("uploaderFiles").getElementsByTagName("li").length;
$('.imgSum').text(length);
}
function uploaderImg() {
var tmpl = '<li class="weui-uploader__file" style="background-image:url(#url#)"></li>';
var $uploaderInput = $("#uploaderInput"); //上传按钮+
var $uploaderFiles = $("#uploaderFiles"); //图片列表
var $galleryImg = $(".weui-gallery__img");//相册图片地址
var $gallery = $(".weui-gallery");
$uploaderInput.on("change", function(e){
var src, url = window.URL || window.webkitURL || window.mozURL, files = e.target.files;
var length = document.getElementById("uploaderFiles").getElementsByTagName("li").length;
if(length>7){
alert("最多只能上传八张图片!");
return;
}
for (var i = 0, len = files.length; i < len; ++i) {
var file = files[i];
uploadFiles.push(file);
console.log(uploadFiles);
if (url) {
src = url.createObjectURL(file);
} else {
src = e.target.result;
}
$uploaderFiles.append($(tmpl.replace('#url#', src)));
sumImgSize();
}
});
var index; //第几张图片
$uploaderFiles.on("click", "li", function(){
index = $(this).index();
$galleryImg.attr("style", this.getAttribute("style"));
console.log(this)
$gallery.fadeIn(100);
});
$gallery.on("click", function(){
$gallery.fadeOut(100);
});
//删除图片
$(".weui-gallery__del").click(function() {
$uploaderFiles.find("li").eq(index).remove();
//delete uploadFiles[index];
uploadFiles.splice(index,1);
console.log(uploadFiles);
sumImgSize();
});
}
function uoloaderVideo() {
var $uploaderFiles_video = $("#uploaderFiles_video");
var $uploaderFiles_videoList = $("#uploaderFiles_videoList"); //图片列表
var tmpl = '<li class="weui-uploader__file"><video class="weui-uploader__file" src="#url#" controls="controls"></video></li>';
//上传视频的代码
$uploaderFiles_video.on('change', function(){
var files = this.files[0];
var fileReader = new FileReader(); //创建FileReader对象
fileReader.readAsDataURL(files); //将文件读取为Data URL
fileReader.onload = function(){
$uploaderFiles_videoList.append($(tmpl.replace('#url#', this.result)));
//$('#preview').attr('src', this.result); //更新预览视频的src属性
};
/* var file = this.files[0]; //获取选择的文件
var formData = new FormData(); //创建表单数据对象
formData.append('file', file); //将文件添加到表单数据中
$.ajax({
url: 'upload.php',
type: 'POST',
data: formData,
contentType: false,
processData: false,
success: function(data){
console.log(data); //成功返回后的处理
}
});*/
});
}
function submitTable() {
//没有上传文件
if (uploadFiles === null && Object.keys(uploadFiles).length === 0) {
alert('请先上传文件');
return;
}
var fileList = {};
var filedata = new FormData();
for (var i in uploadFiles) { //用javascript的for/in循环遍历对象的属性
var file = new Object();
var file2 = uploadFiles[i];
file.wdmc = file2.name;
file.size = file2.size;
var fj = file2.wdmc;
file.wdlx = '01';
file.bz = '';
fileList[i] = file;
filedata.append('uploadFiles', uploadFiles[i]);
}
filedata.append('dxId', '11111');
filedata.append('scrId', '11111');
filedata.append('fileDir', "投诉举报");
filedata.append('dirName', "附件资料");
filedata.append('fileList', JSON.stringify(fileList));
$.ajax({
type: "POST",
url: Server_URL+"wdzl/insertWdzl",
data: filedata,
processData: false,
contentType: false,
dataType: 'json',
error: function (data) {
alert('网络出错');
},
success: function (data) {
if (data.code === 'ok') {
alert('上传成功');
uploadFiles = [];//内容置空
location.href="pay.html";
//跳转提交成功页面
} else {
alert(data.msg);
}
}
});
}
</script>
成果展示
项目下
数据库中