代码提交

This commit is contained in:
zhengzheng 2022-05-03 23:08:46 +08:00
parent de51cad5a5
commit af70ac52e8
6 changed files with 194 additions and 373 deletions

View File

@ -12,6 +12,8 @@ import com.wuzhen.framework.shiro.util.AuthorizationUtils;
import com.wuzhen.system.domain.ActiveInfo;
import com.wuzhen.system.service.IActiveInfoService;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
@ -19,10 +21,7 @@ import org.springframework.ui.ModelMap;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.List;
@ -35,6 +34,9 @@ import java.util.List;
@RequestMapping("/active/info")
public class ActiveInfoController extends BaseController
{
private static final Logger logger = LoggerFactory.getLogger(ActiveInfoController.class);
private String prefix = "active/info";
@Autowired
@ -99,34 +101,10 @@ public class ActiveInfoController extends BaseController
@ResponseBody
public AjaxResult addSave(@Validated ActiveInfo activeInfo)
{
MultipartFile[] files = activeInfo.getActivePic();
MultipartFile file = files[0];
// 获取上传文件名
String filename = files[0].getOriginalFilename();
if (!"".equals(filename)){
// 定义上传文件保存路径
String path = RuoYiConfig.getLPUploadPath();
// 新建文件
File filepath = new File(path, filename);
// 判断路径是否存在如果不存在就创建一个
if (!filepath.getParentFile().exists()) {
filepath.getParentFile().mkdirs();
}
String picUrl = path + File.separator + filename;
try {
// 写入文件
file.transferTo(new File(picUrl));
} catch (IOException e) {
e.printStackTrace();
}
activeInfo.setActivePicUrl(lp+filename);
}
logger.info(activeInfo.toString());
activeInfo.setCreateBy(getLoginName());
AuthorizationUtils.clearAllCachedAuthorizationInfo();
return toAjax(activeInfoService.insertActive(activeInfo));
}
/**
@ -207,35 +185,7 @@ public class ActiveInfoController extends BaseController
return toAjax(activeInfoService.updateActive(activeInfo));
}
// /**
// * 角色分配数据权限
// */
// @GetMapping("/authDataScope/{roleId}")
// public String authDataScope(@PathVariable("roleId") Long roleId, ModelMap mmap)
// {
// mmap.put("role", roleService.selectRoleById(roleId));
// return prefix + "/dataScope";
// }
// /**
// * 保存角色分配数据权限
// */
// @RequiresPermissions("system:role:edit")
// @Log(title = "角色管理", businessType = BusinessType.UPDATE)
// @PostMapping("/authDataScope")
// @ResponseBody
// public AjaxResult authDataScopeSave(SysRole role)
// {
// roleService.checkRoleAllowed(role);
// roleService.checkRoleDataScope(role.getRoleId());
// role.setUpdateBy(getLoginName());
// if (roleService.authDataScope(role) > 0)
// {
// setSysUser(userService.selectUserById(getUserId()));
// return success();
// }
// return error();
// }
@RequiresPermissions("active:info:remove")
@Log(title = "活动管理", businessType = BusinessType.DELETE)
@ -246,34 +196,7 @@ public class ActiveInfoController extends BaseController
return toAjax(activeInfoService.deleteActiveByIds(ids));
}
/**
// * 校验角色名称
// */
// @PostMapping("/checkRoleNameUnique")
// @ResponseBody
// public String checkRoleNameUnique(SysRole role)
// {
// return roleService.checkRoleNameUnique(role);
// }
//
// /**
// * 校验角色权限
// */
// @PostMapping("/checkRoleKeyUnique")
// @ResponseBody
// public String checkRoleKeyUnique(SysRole role)
// {
// return roleService.checkRoleKeyUnique(role);
// }
//
// /**
// * 选择菜单树
// */
// @GetMapping("/selectMenuTree")
// public String selectMenuTree()
// {
// return prefix + "/tree";
// }
/**
* 状态修改
@ -287,157 +210,7 @@ public class ActiveInfoController extends BaseController
return toAjax(activeInfoService.updateActive(activeInfo));
}
// /**
// * 分配用户
// */
// @RequiresPermissions("system:role:edit")
// @GetMapping("/authUser/{roleId}")
// public String authUser(@PathVariable("roleId") Long roleId, ModelMap mmap)
// {
// mmap.put("role", roleService.selectRoleById(roleId));
// return prefix + "/authUser";
// }
// /**
// * 查询已分配用户角色列表
// */
// @RequiresPermissions("system:role:list")
// @PostMapping("/authUser/allocatedList")
// @ResponseBody
// public TableDataInfo allocatedList(SysUser user)
// {
// startPage();
// List<SysUser> list = userService.selectAllocatedList(user);
// return getDataTable(list);
// }
// /**
// * 取消授权
// */
// @RequiresPermissions("system:role:edit")
// @Log(title = "角色管理", businessType = BusinessType.GRANT)
// @PostMapping("/authUser/cancel")
// @ResponseBody
// public AjaxResult cancelAuthUser(SysUserRole userRole)
// {
// return toAjax(roleService.deleteAuthUser(userRole));
// }
/**
* 批量取消授权
*/
// @RequiresPermissions("system:role:edit")
// @Log(title = "角色管理", businessType = BusinessType.GRANT)
// @PostMapping("/authUser/cancelAll")
// @ResponseBody
// public AjaxResult cancelAuthUserAll(Long roleId, String userIds)
// {
// return toAjax(roleService.deleteAuthUsers(roleId, userIds));
// }
// /**
// * 选择用户
// */
// @GetMapping("/authUser/selectUser/{roleId}")
// public String selectUser(@PathVariable("roleId") Long roleId, ModelMap mmap)
// {
// mmap.put("role", roleService.selectRoleById(roleId));
// return prefix + "/selectUser";
// }
// /**
// * 查询未分配用户角色列表
// */
// @RequiresPermissions("system:role:list")
// @PostMapping("/authUser/unallocatedList")
// @ResponseBody
// public TableDataInfo unallocatedList(SysUser user)
// {
// startPage();
// List<SysUser> list = userService.selectUnallocatedList(user);
// return getDataTable(list);
// }
// /**
// * 批量选择用户授权
// */
// @RequiresPermissions("system:role:edit")
// @Log(title = "角色管理", businessType = BusinessType.GRANT)
// @PostMapping("/authUser/selectAll")
// @ResponseBody
// public AjaxResult selectAuthUserAll(Long roleId, String userIds)
// {
// roleService.checkRoleDataScope(roleId);
// return toAjax(roleService.insertAuthUsers(roleId, userIds));
// }
public static void uploadFile(byte[] file, String filePath, String fileName) throws Exception {
File targetFile = new File(filePath);
if (!targetFile.exists()) {
targetFile.mkdirs();
}
FileOutputStream out = new FileOutputStream(filePath+"/"+ fileName);
out.write(file);
out.flush();
out.close();
}
//处理文件上传
@ResponseBody //返回json数据
@RequestMapping(value = "upload", method = RequestMethod.POST)
public JSONObject uploadImg( @RequestPart("myFile") MultipartFile[] files) {
JSONObject jo = new JSONObject();//实例化json数据
String fileNameArr[] =null;
if (files==null||files.length==0) {
jo.put("success", 0);
jo.put("fileName",new String[]{});
}else {
fileNameArr=new String[files.length];
}
for ( int i =0 ;i<files.length;i++) {
String fileName = System.currentTimeMillis()+files[i].getOriginalFilename();
String filePath = RuoYiConfig.getLPUploadPath();
try {
uploadFile(files[i].getBytes(), filePath, fileName);
fileNameArr[i] = fileName;
} catch (Exception e) {
// TODO: handle exception
}
}
jo.put("success", 1);
jo.put("fileName", fileNameArr);
//返回json
return jo;
}
@ResponseBody //返回json数据
@RequestMapping("deleteImages")
public String deleteImages(HttpServletRequest request) {
String resultInfo = null;
String filePath = request.getParameter("filePath");
//这里是可以在控制器分割字符的一个方法
//int lastIndexOf = filePath.lastIndexOf("/");
//String sb = filePath.substring(lastIndexOf+1,filePath.length());
//由于我们只获取了图片的名称并没有获取到所有的地址所以我们需要去给他进行添加存放图片的地址
File file = new File(RuoYiConfig.getLPUploadPath()+filePath);
if (file.exists()) {
if (file.delete()) {
resultInfo = "1-删除成功";
}else {
resultInfo = "0-删除失败";
}
}else {
resultInfo = "文件不存在!";
}
return resultInfo;
}
}

View File

@ -100,14 +100,53 @@ public class CommonController
/**
* 通用上传请求多个
*/
@PostMapping("/uploads")
@PostMapping("/uploadsLp")
@ResponseBody
public AjaxResult uploadFiles(List<MultipartFile> files) throws Exception
public AjaxResult uploadFilesLp(List<MultipartFile> files) throws Exception
{
try
{
// 上传文件路径
String filePath = RuoYiConfig.getUploadPath();
String filePath = RuoYiConfig.getLPUploadPath();
List<String> urls = new ArrayList<String>();
List<String> fileNames = new ArrayList<String>();
List<String> newFileNames = new ArrayList<String>();
List<String> originalFilenames = new ArrayList<String>();
for (MultipartFile file : files)
{
// 上传并返回新文件名称
String fileName = FileUploadUtils.upload(filePath, file);
String url = serverConfig.getUrl() + fileName;
urls.add(url);
fileNames.add(fileName);
newFileNames.add(FileUtils.getName(fileName));
originalFilenames.add(file.getOriginalFilename());
}
AjaxResult ajax = AjaxResult.success();
ajax.put("urls", StringUtils.join(urls, FILE_DELIMETER));
ajax.put("fileNames", StringUtils.join(fileNames, FILE_DELIMETER));
ajax.put("newFileNames", StringUtils.join(newFileNames, FILE_DELIMETER));
ajax.put("originalFilenames", StringUtils.join(originalFilenames, FILE_DELIMETER));
return ajax;
}
catch (Exception e)
{
return AjaxResult.error(e.getMessage());
}
}
/**
* 通用上传请求多个
*/
@PostMapping("/uploadsFp")
@ResponseBody
public AjaxResult uploadFilesFp(List<MultipartFile> files) throws Exception
{
try
{
// 上传文件路径
String filePath = RuoYiConfig.getFPUploadPath();
List<String> urls = new ArrayList<String>();
List<String> fileNames = new ArrayList<String>();
List<String> newFileNames = new ArrayList<String>();

View File

@ -4,10 +4,13 @@
<th:block th:include="include :: header('新增活动')"/>
<th:block th:include="include :: datetimepicker-css"/>
<!-- <th:block th:include="include :: ztree-css" />-->
<th:block th:include="include :: bootstrap-fileinput-css"/>
</head>
<body class="white-bg">
<div class="wrapper wrapper-content animated fadeInRight ibox-content">
<form class="form-horizontal m" id="form-role-add" enctype="multipart/form-data">
<input id="lpFilesName" name="lpFilesName" type="hidden"/>
<div class="form-group">
<label class="col-sm-3 control-label is-required">活动标题:</label>
<div class="col-sm-8">
@ -38,25 +41,13 @@
</div>
</div>
<div class="form-group">
<label class="col-sm-3 control-label is-required">活动图片:</label>
<div class="col-sm-8">
<!-- <label for="uploadFile">或者 上传本地文件</label>-->
<input type="file" class="form-control-file" id="activePic" name="activePic" multiple>
<p id="url"><img src="" width=200></p>
<input type="button" id="button" value="上传">
<input type="button" id="t_button" value="取消上传">
<!-- <input class="form-control" type="text" name="activePic" id="activePic" required>-->
</div>
<div class="form-group form-inline" style="width:100%;padding-left: 60px;">
<div class="col-sm-8">
<img id="showUserImg0" width="30%" height="30%" />
<img id="showUserImg1" width="30%" height="30%" />
<img id="showUserImg2" width="30%" height="30%" />
<img id="showUserImg3" width="30%" height="30%" />
<img id="showUserImg4" width="30%" height="30%" />
<div class="file-loading">
<input id="multipleFile" name="files" type="file" multiple>
</div>
</div>
@ -111,6 +102,7 @@
<th:block th:include="include :: datetimepicker-js"/>
<script th:src="@{/js/jquery-ui-1.10.4.min.js}"></script>
<th:block th:include="include :: datetimepicker-js"/>
<th:block th:include="include :: bootstrap-fileinput-js"/>
<script th:src="@{/ajax/libs/beautifyhtml/beautifyhtml.js}"></script>
<!-- <th:block th:include="include :: ztree-js" />-->
<script type="text/javascript">
@ -118,127 +110,111 @@
</script>
<script type="text/javascript">
function submitHandler() {
add();
}
function submitHandler() {
add();
}
function add() {
function add() {
var formData = new FormData($("#form-role-add")[0])
$.ajax({
cache: false,
contentType: false,
processData: false,
type: "POST",
url: ctx + "active/info/add",
data: formData,
async: false,
error: function (request) {
$.modal.alertError("系统错误");
},
success: function (data) {
$.operate.successCallback(data);
}
});
}
<!-- var activeTitle = $("input[name='activeTitle']").val();-->
<!-- var activeDesc =$("textarea[name='activeDesc']").val();-->
<!-- var activeType = $("select[name='activeType']").val();-->
<!-- var activeStartDate = $("input[name='activeStartDate']").val();-->
<!-- var activeEndDate = $("input[name='activeEndDate']").val();-->
<!-- var status = $("input[id='status']").is(':checked') == true ? 0 : 1;-->
<!-- var remark = $("input[name='remark']").val();-->
var activePic = $('#activePic')[0].files;
var formData = new FormData($("#form-role-add")[0])
formData.append('activePic', activePic);
<!-- formData.append('activeDesc', activeDesc);-->
<!-- formData.append('activeType', activeType);-->
<!-- formData.append('activeStartDate', activeStartDate);-->
<!-- formData.append('activeEndDate', activeEndDate);-->
<!-- formData.append('status', status);-->
<!-- formData.append('remark', remark);-->
$.ajax({
cache: false,
contentType: false,
processData: false,
type : "POST",
url : ctx + "active/info/add",
data : formData,
async : false,
error : function(request) {
$.modal.alertError("系统错误");
},
success : function(data) {
$.operate.successCallback(data);
}
});
}
$(function () {
$("#button").click(function () {
var form = new FormData();
var files = document.getElementById("activePic").files;
if(files.length > 5) {
alert("上传图片不能超过5张");
return 0;
}
$.each(files, function (i, file) {
form.append('myFile', file); });
$.ajax({
url: ctx + "active/info/upload",
data: form,
cache: false,
async: false,
type: "POST",
dataType: 'json',
processData: false,
contentType: false,
success: function (data) {
if (data) {
alert(data);
var imgs = data.fileName;
$.each(imgs, function (i, path) {
var id = "#showUserImg"+i;
alert(id+path);
$(id).attr("src", "/lp/"+path );
});
<!-- var pic="/lp/"+data.fileName;-->
<!-- alert(pic);-->
<!-- $("#url img").attr("src",pic);-->
<!-- $("#file1").val("/lp/"+data.fileName);-->
} else {
alert("失败");
}
},
error: function (er) {
alert(JSON.stringify(data));
$(function () {
// TODO: 上传
// 多图上传
$("#multipleFile").fileinput({
uploadUrl: ctx + 'common/uploadsLp',
uploadAsync: false
}).on('filebatchuploadsuccess', function (event, data, previewId, index) {
console.log('filebatchuploadsuccess', event, data, previewId, index);
var rsp = data.response;
var urls = rsp.newFileNames || '';
var value = $("#lpFilesName").val() || '';
var list = [];
if (value) {
var list = value.split(',');
}
list = list.concat(urls.split(','))
$("#lpFilesName").val(list.join(','));
var a = $("#lpFilesName").val();
alert(rsp.newFileNames);
alert(a);
}).on('fileuploaded', function (event, data, previewId, index) {
console.log('fileuploaded', event, data, previewId, index);
var rsp = data.response;
var value = $("#lpFilesName").val() || '';
var list = [];
var res = [];
var r_val = rsp.newFileNames;
res.push(r_val);
var list = value.split(',');
list.forEach(function (item) {
if (item !== r_val) {
res.push(item);
}
});
});
});
})
$("#lpFilesName").val(res.join(','));
var b = $("#lpFilesName").val();
alert(b);
}).on('fileremoved', function (event, id, index) {
alert('进入删除');
alert(id);
var value = $("#lpFilesName").val() || '';
var list = value.split(',');
var res = [];
list.forEach(function (item) {
if (item !== data) {
res.push(item);
}
})
$("#lpFilesName").val(res.join(','));
var c = $("#lpFilesName").val();
alert(c);
}).on('filesuccessremove', function (event, data, previewId, index) {
alert('点击单个预览的删除按钮');
alert(data);
var value = $("#lpFilesName").val() || '';;
var list = value.split(',');
var res = [];
list.forEach(function (item) {
if (item !== data) {
res.push(item);
}
})
$("#lpFilesName").val(res.join(','));
}).on('filecleared', function (event, data, msg) {
alert('全部删除');
alert(data);
$("#lpFilesName").val('');
var d = $("#lpFilesName").val();
alert(d);
})
});
</script>
</body>
</html>

View File

@ -122,7 +122,10 @@ public class FileUploadUtils
*/
public static final String extractFilename(MultipartFile file)
{
return StringUtils.format("{}/{}_{}.{}", DateUtils.datePath(),
// return StringUtils.format("{}/{}_{}.{}", DateUtils.datePath(),
// FilenameUtils.getBaseName(file.getOriginalFilename()), Seq.getId(Seq.uploadSeqType), getExtension(file));
return StringUtils.format("{}_{}.{}",
FilenameUtils.getBaseName(file.getOriginalFilename()), Seq.getId(Seq.uploadSeqType), getExtension(file));
}

View File

@ -56,10 +56,32 @@ public class ActiveInfo extends BaseEntity {
@Excel(name = "活动类型")
private String activeType;
public String getLpFilesName() {
return lpFilesName;
}
public void setLpFilesName(String lpFilesName) {
this.lpFilesName = lpFilesName;
}
/**
* 活动图片
* 活动列表
*/
private MultipartFile[] activePic;
private String lpFilesName;
public String getFpFilesName() {
return fpFilesName;
}
public void setFpFilesName(String fpFilesName) {
this.fpFilesName = fpFilesName;
}
/**
* 首页列表
*/
private String fpFilesName;
@ -202,13 +224,13 @@ public class ActiveInfo extends BaseEntity {
this.activeType = activeType;
}
public MultipartFile[] getActivePic() {
return activePic;
}
public void setActivePic(MultipartFile[] activePic) {
this.activePic = activePic;
}
// public MultipartFile[] getActivePic() {
// return activePic;
// }
//
// public void setActivePic(MultipartFile[] activePic) {
// this.activePic = activePic;
// }
public String getStatus() {
return status;
@ -247,11 +269,13 @@ public class ActiveInfo extends BaseEntity {
.append("activeStartDate", getActiveStartDate())
.append("activeEndDate", getActiveEndDate())
.append("activeType", getActiveType())
.append("activePic", getActivePic())
.append("createBy", getCreateBy())
.append("createTime", getCreateTime())
.append("updateBy", getUpdateBy())
.append("updateTime", getUpdateTime())
.append("fpFilesName", getFpFilesName())
.append("lpFilesName", getLpFilesName())
.append("remark", getRemark())
.append("address", getAddress())
.toString();

View File

@ -23,6 +23,8 @@ PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
<result property="remark" column="remark" />
<result property="delFlag" column="del_flag" />
<result property="address" column="address" />
<result property="lpFilesName" column="lp_files_name" />
<result property="fpFilesName" column="fp_files_name" />
<result property="isEnroll" column="is_enroll" />
</resultMap>
@ -123,7 +125,9 @@ PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
<if test="remark != null and remark != ''">remark,</if>
<if test="createBy != null and createBy != ''">create_by,</if>
<if test="address != null and address != ''">address,</if>
<if test="isEnroll != null and isEnroll != ''">is_enroll</if>
<if test="lpFilesName != null and lpFilesName != ''">lp_files_name,</if>
<if test="fpFilesName != null and fpFilesName != ''">fp_files_name,</if>
<if test="isEnroll != null and isEnroll != ''">is_enroll,</if>
create_time
)values(
<if test="activeTitle != null and activeTitle !=''">#{activeTitle},</if>
@ -136,6 +140,8 @@ PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
<if test="remark != null and remark != ''">#{remark},</if>
<if test="createBy != null and createBy != ''">#{createBy},</if>
<if test="address != null and address != ''">#{address},</if>
<if test="lpFilesName != null and lpFilesName != ''">#{lpFilesName},</if>
<if test="fpFilesName != null and fpFilesName != ''">#{fpFilesName},</if>
<if test="isEnroll != null and isEnroll != ''">#{isEnroll},</if>
sysdate()
)