···
package whm.sys.controller;
//创建一个FileController文件,用来做文件上传和图片下载
import cn.hutool.core.date.DateUtil;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import whm.commons.AppFileUtils;
import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
/**
- @author Vijay
- @date 2020/4/14 -19:42
/
@RestController
@RequestMapping("file")
public class FileController {
/*- 文件上传
- @param mf
- @return
/
@RequestMapping("uploadFile")
public Map<String,Object> uploadFile(MultipartFile mf) {
//1.得到文件名
String lastName = mf.getOriginalFilename();
//2.根据旧的文件名生成新的文件名
String newName = AppFileUtils.createNewFileName(lastName);
//3.得到当前日期的字符串
String dirName = DateUtil.format(new Date(), "yyyy-MM-dd");
//4.构造文件夹
File dirFile = new File(AppFileUtils.UPLOAD_PATH,dirName);
//5.判断当前文件夹是否存在
if (!dirFile.exists())
{
dirFile.mkdirs();
}
//6.构造文件对象
File file = new File(dirFile,newName+"_temp");
//7.把mf里面的图片信息写入file
try {
mf.transferTo(file);
} catch (IOException e) {
e.printStackTrace();
}
Map<String, Object> map=new HashMap<>();
map.put("path",dirName+"/"+newName+"_temp");
return map;
}
/* - 图片下载
*/
@RequestMapping("showImageByPath")
public ResponseEntity<Object> showImageByPath(String path){
return AppFileUtils.createResponseEntity(path);
}
}
···
将文件上传和下载的核心方法封装成AppFileUtils类
···
package whm.commons;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.IdUtil;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
/**
-
@author
/
public class AppFileUtils {
/*- 文件上传的保存路径 默认值
/
public static String UPLOAD_PATH="F:/upload/";
static {
//通过反射的方式,读取配置文件的存储地址
InputStream stream = AppFileUtils.class.getClassLoader().getResourceAsStream("file.properties");//不用默认路径可以设置一个properties文件用来读取
Properties properties=new Properties();
try {
properties.load(stream);
} catch (IOException e) {
e.printStackTrace();
}
String property = properties.getProperty("filepath");
if(null!=property) {
UPLOAD_PATH=property;
}
}
/* - 根据文件老名字得到新名字
- @param oldName 文件老名字
- @return 新名字由32位随机数加图片后缀组成
/
public static String createNewFileName(String oldName) {
//获取文件名后缀
String stuff=oldName.substring(oldName.lastIndexOf("."), oldName.length());
//将UUID与文件名后缀进行拼接,生成新的文件名 生成的UUID为32位
return IdUtil.simpleUUID().toUpperCase()+stuff;
}
/* - 文件下载
- @param path
- @return
*/
public static ResponseEntity<Object> createResponseEntity(String path) {
//1,构造文件对象
File file=new File(UPLOAD_PATH, path);
if(file.exists()) {
//将下载的文件,封装byte[]
byte[] bytes=null;
try {
bytes = FileUtil.readBytes(file);
} catch (Exception e) {
e.printStackTrace();
}
//创建封装响应头信息的对象
HttpHeaders header=new HttpHeaders();
//封装响应内容类型(APPLICATION_OCTET_STREAM 响应的内容不限定)
header.setContentType(MediaType.APPLICATION_OCTET_STREAM);
//创建ResponseEntity对象
ResponseEntity<Object> entity= new ResponseEntity<Object>(bytes, header, HttpStatus.CREATED);
return entity;
}
return null;
}
/**
- 更该图片的名字 去掉_temp
- @param goodsImg
- @return
*/
public static String renameFile(String goodsImg) {
File file = new File(UPLOAD_PATH,goodsImg);
String replace = goodsImg.replace("_temp","");
if (file.exists()){
file.renameTo(new File(UPLOAD_PATH,replace));
}
return replace;
}
/**
- 根据老路径删除图片
- @param oldPath
*/
public static void removeFileByPath(String oldPath) {
//图片的路径不是默认图片的路径
if (!oldPath.equals(Constast.DEFAULT_IMG_GOODS)){
File file = new File(UPLOAD_PATH,oldPath);
if (file.exists()){
file.delete();
}
}
}
- 文件上传的保存路径 默认值
}
···
创建一个html文件
···
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org"
xmlns:shiro="http://www.thymeleaf.org/thymeleaf-extras-shiro"
<head>
<meta charset="UTF-8">
<title>商品管理</title>
<meta name="renderer" content="webkit">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<meta http-equiv="Access-Control-Allow-Origin" content="*">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
<meta name="apple-mobile-web-app-status-bar-style" content="black">
<meta name="apple-mobile-web-app-capable" content="yes">
<meta name="format-detection" content="telephone=no">
<link rel="icon" href="/favicon.ico">
<link rel="stylesheet" href="/resources/layui/css/layui.css" media="all"/>
<link rel="stylesheet" href="/resources/css/public.css" media="all"/>
<style>
input#search_provideridTree_select_input_id {
border-radius: 10px;
height: 30px;
margin-top: 4px;
}
input#provideridTree_select_input_id {
border-radius: 10px;
height: 30px;
margin-top: 4px;
}
input#leaderprovideridTree_select_input_id {
border-radius: 10px;
height: 30px;
margin-top: 4px;
}
input.layui-input.layui-unselect {
border-radius: 10px;
height: 30px;
margin-top: 4px;
}
</style>
</head>
<body class="childrenBody">
<fieldset class="layui-elem-field layui-field-title" style="margin-top: 30px;">
<legend>商品管理</legend>
</fieldset>
<blockquote class="layui-elem-quote">
<form action="" method="post" id="searchFrm" lay-filter="searchFrm" class="layui-form">
<div class="layui-form-item">
<div class="layui-inline">
<label class="layui-form-label">供应商</label>
<div class="layui-input-inline">
<select name="providerid" id="select_providerid">
<option value="0">请选择供应商</option>
</select>
</div>
</div>
<div class="layui-inline">
<label class="layui-form-label">商品名称</label>
<div class="layui-input-inline">
<input type="text" name="goodsname" id="goodsname" class="layui-input input-radius"
placeholder="请输入商品名称">
</div>
</div>
<div class="layui-inline">
<label class="layui-form-label">生产批号</label>
<div class="layui-input-inline">
<input type="text" name="productcode" id="productcode" class="layui-input input-radius" placeholder="请输入生产批号">
</div>
</div>
<div class="layui-inline">
<label class="layui-form-label">批准文号</label>
<div class="layui-input-inline">
<input type="text" name="promitcode" id="promitcode" class="layui-input input-radius" placeholder="请输入批准文号">
</div>
</div>
</div>
<div class="layui-form-item">
<div class="layui-inline">
<label class="layui-form-label">商品描述</label>
<div class="layui-input-inline">
<input type="text" name="description" id="description" class="layui-input input-radius"
placeholder="请输入商品描述">
</div>
</div>
<div class="layui-inline">
<label class="layui-form-label">商品规格</label>
<div class="layui-input-inline">
<input type="text" name="size" id="size" class="layui-input input-radius" placeholder="请输入商品规格">
</div>
</div>
<div class="layui-inline" style="padding-left: 3%">
<button type="button" class="layui-btn layui-btn-sm layui-btn-radius" lay-submit="" lay-filter="doSearch"><i
class="layui-icon layui-icon-search layui-icon-normal"></i>查询
</button>
<button type="reset" class="layui-btn layui-btn-sm layui-btn-radius layui-btn-warm"><i
class="layui-icon layui-icon-refresh"></i><span>重置</span>
</button>
</div>
</div>
</form>
</blockquote>
<table class="layui-hide" id="goodsTable" lay-filter="goodsTable"></table>
<div id="goodsToolBar" style="display: none">
<button type="button" lay-event="add" shiro:hasPermission="goods:create" class="layui-btn layui-btn-sm layui-btn-normal layui-btn-radius">
<i class="layui-icon layui-icon-add-1"></i>添加商品
</button>
<button type="button" lay-event="batchDelete" class="layui-btn layui-btn-sm layui-btn-danger layui-btn-radius" shiro:hasPermission="goods:batchdelete">
<i class="layui-icon layui-icon-delete"></i>批量删除
</button>
</div>
<div id="goodsRowBar" style="display: none;">
<button type="button" lay-event="update" class="layui-btn layui-btn-sm layui-btn-radius"><i
class="layui-icon layui-icon-edit" shiro:haspermission="goods:update"></i>编辑
</button>
<button type="button" lay-event="delete" class="layui-btn layui-btn-sm layui-btn-danger layui-btn-radius"><i
class="layui-icon layui-icon-delete" shiro:haspermission="goods:delete"></i>删除
</button>
</div>
</div>
<div id="addOrUpdateDiv" style="display: none;padding: 10px;padding-right: 5%">
<form action="" method="post" class="layui-form" id="dataFrm" lay-filter="dataFrm">
<div class="layui-col-md12 layui-col-xs12">
<div class="layui-row layui-col-space10">
<div class="layui-col-md9 layui-col-xs7">
<div class="layui-form-item magt3">
<label class="layui-form-label">供应商</label>
<div class="layui-input-block">
<select name="providerid" id="providerid">
<option value="0">请选择供应商</option>
</select>
</div>
</div>
<div class="layui-form-item">
<label class="layui-form-label">商品名称</label>
<div class="layui-input-block">
<input type="hidden" name="id">
<input type="text" class="layui-input input-radius" name="goodsname" lay-verify="required" placeholder="请输入商品名称">
</div>
</div>
<div class="layui-form-item">
<label class="layui-form-label">商品描述</label>
<div class="layui-input-block">
<input type="text" class="layui-input input-radius" name="description" lay-verify="required" placeholder="请输入商品描述">
</div>
</div>
</div> (重点代码在这里)
<div class="layui-col-md3 layui-col-xs5">
<div class="layui-upload-list thumbBox mag0 magt3">
<input type="hidden" name="goodsimg" id="goodsimg" value="/file/showImageByPath?path=images/noDefaultImage.jpg">
<img class="layui-upload-img thumbImg" src="/file/showImageByPath?path=images/noDefaultImage.jpg">
</div>
</div>
</div>
<div class="layui-form-item magb0">
<div class="layui-inline">
<label class="layui-form-label">产地</label>
<div class="layui-input-inline">
<input type="text" class="layui-input input-radius" name="produceplace" lay-verify="required" placeholder="请输入商品产地">
</div>
</div>
<div class="layui-inline">
<label class="layui-form-label">包装</label>
<div class="layui-input-inline">
<input type="text" class="layui-input input-radius" name="goodspackage" lay-verify="required" placeholder="请输入商品包装">
</div>
</div>
<div class="layui-inline">
<label class="layui-form-label">规格</label>
<div class="layui-input-inline">
<input type="text" class="layui-input input-radius" name="size" lay-verify="required" placeholder="请输入商品规格">
</div>
</div>
<div class="layui-inline">
<label class="layui-form-label">生产批号</label>
<div class="layui-input-inline">
<input type="text" class="layui-input input-radius" name="productcode" lay-verify="required" placeholder="请输入商品生产批号">
</div>
</div>
<div class="layui-inline">
<label class="layui-form-label">批准文号</label>
<div class="layui-input-inline">
<input type="text" class="layui-input input-radius" name="promitcode" lay-verify="required" placeholder="请输入商品批准文号">
</div>
</div>
<div class="layui-inline">
<label class="layui-form-label">销售价格</label>
<div class="layui-input-inline">
<input type="text" class="layui-input input-radius" name="price" lay-verify="required|number" placeholder="请输入商品销售价格">
</div>
</div>
<div class="layui-inline">
<label class="layui-form-label">库存量</label>
<div class="layui-input-inline">
<input type="text" class="layui-input input-radius" name="number" lay-verify="required|number" placeholder="请输入商品库存量">
</div>
</div>
<div class="layui-inline">
<label class="layui-form-label">预警值</label>
<div class="layui-input-inline">
<input type="text" class="layui-input input-radius" name="dangernum" lay-verify="required|number" placeholder="请输入商品预警值">
</div>
</div>
<div class="layui-inline">
<label class="layui-form-label">是否可用</label>
<div class="layui-input-inline">
<input type="radio" name="available" value="1" title="可用" checked="">
<input type="radio" name="available" value="0" title="不可用" >
</div>
</div>
</div>
</div>
<div class="layui-form-item">
<div class="layui-input-block" style="text-align: center;padding-right: 7%">
<button type="button" class="layui-btn layui-btn-radius" lay-submit="" lay-filter="doSubmit" id="doSubmit"><i
class="layui-icon layui-icon-search layui-icon-normal"></i>提交
</button>
<button type="reset" class="layui-btn layui-btn-radius layui-btn-warm"><i
class="layui-icon layui-icon-refresh"></i><span>重置</span>
</button>
</div>
</div>
</form>
</div>
<script type="text/javascript" src="/resources/layui/layui.js"></script>
<script type="text/javascript">
layui.use(['jquery', 'form', 'layer', 'laydate', 'table','layedit','upload'], function () {
var .ajax({
url: "/good/loadAllgoodsProviders", //请求的URL地址
type: "GET", //请求方法,GET、POST、PUT、DELETE在这里设置
timeout: 5000, //超时时间
dataType: 'json',
//返回的数据格式:json/xml/html/script/jsonp/text
success: function (res) { //成功的回调函数
var data=res.data;
var html=' <option value="0">请选择供应商</option>';
var dom=.each(data,function (index,item) {
html+=' <option value='+item.id+'>'+item.providername+'</option>';
})
dom.html(html);
form.render("select")
}
})
//监控模糊查询按钮事件
form.on("submit(doSearch)", function (data) {
tableIns.reload({
where: data.field,
page: {
curr: 1
}
});
return false;
});
//监控工具条事件
//批量删除和添加
table.on("toolbar(goodsTable)", function (obj) {
switch (obj.event) {
case 'add':
openAdd();
break;
case 'batchDelete':
batchDelete();
break;
};
});
//监控行工具条事件
//查看,编辑,删除
table.on("tool(goodsTable)",function (obj) {
//获取当前行数据
var data = obj.data;
switch (obj.event){
case 'show':
showgoods(data);
break;
case 'update':
updategoods(data);
break;
case 'delete':
deletegoods(data);
break;
};
});
//打开添加的弹出层
function openAdd() {
mainIndex = layer.open({
type:1,
content:$("#addOrUpdateDiv"),
area:['800px','550px'],
title:'添加商品',
success:function () {
$('#dataFrm')[0].reset();
type="POST";
$.ajax({
url: "/good/loadAllgoodsProviders", //请求的URL地址
type: "GET", //请求方法,GET、POST、PUT、DELETE在这里设置
timeout: 5000, //超时时间
dataType: 'json',
success: function (res) { //成功的回调函数
var data=res.data;
var html=' <option value="0">请选择供应商</option>';
var dom=$("#providerid");
$.each(data,function (index,item) {
html+=' <option value='+item.id+'>'+item.providername+'</option>';
})
dom.html(html);
form.render("select")
}
})
//设置默认为无图片
$(".thumbImg").attr("src","/file/showImageByPath?path=images/noDefaultImage.jpg");
$("#goodsimg").val("/images/noDefaultImage.jpg");
}
});
};
//打开修改的弹出层
function updategoods(data) {
mainIndex = layer.open({
type:1,
content:$("#addOrUpdateDiv"),
area:['800px','550px'],
title:'修改商品',
success:function () {
//装载新的数据
$('#dataFrm')[0].reset();
form.val("dataFrm",data);
$(".thumbImg").attr("src",'/file/showImageByPath?path='+data.goodsimg);
$.ajax({
url: "/good/loadAllgoodsProviders", //请求的URL地址
type: "GET", //请求方法,GET、POST、PUT、DELETE在这里设置
timeout: 5000, //超时时间
dataType: 'json',
success: function (res) { //成功的回调函数
var html=' <option value="0">请选择供应商</option>';
var dom=$("#providerid");
var resdata=res.data;
$.each(resdata,function (index,item) {
if (data.providerid===item.id)
{
html+=' <option value='+item.id+' selected>'+item.providername+'</option>';
}
else
{
html+=' <option value='+item.id+'>'+item.providername+'</option>';
}
})
dom.html(html);
form.render("select")
}
})
//装载新的数据
type="PUT";
}
});
};
//提交修改和添加的弹出层数据
$("#doSubmit").click(function () {
//同步富文本和textarea里面的内容
var datas = $("#dataFrm").serialize();
$.ajax({
url:"/good/goods", //请求的URL地址
type:type, //请求方法,GET、POST、PUT、DELETE在这里设置
timeout:5000, //超时时间
dataType:'json',
data:datas,
//返回的数据格式:json/xml/html/script/jsonp/text
success:function(data){ //成功的回调函数
if (data.code==200){
tableIns.reload();
layer.msg(data.msg) //设置id为result的标签的html内容为返回的data数据
layer.close(mainIndex);
}
else
{
layer.msg(data.msg) //设置id为result的标签的html内容为返回的data数据
}
},
})
});
//文件上传(重点代码在这里)
upload.render({
elem: '.thumbBox',
url: '/file/uploadFile',(后台请求)
acceptMime:'image/*',
field:'mf',
method : "post",
done: function(res, index, upload){
var path=res.path;
$('.thumbImg').attr('src','/file/showImageByPath?path='+path);
$('.thumbBox').css("background","#fff");
//给隐藏域赋值
$("#goodsimg").val(path);
}+
});
//删除
function deletegoods(data) {
layer.confirm('你确定要删除这条数据吗?',{icon: 3,title:'提示'},function (index) {
$.ajax({
url:"/good/goods", //请求的URL地址
type:"DELETE", //请求方法,GET、POST、PUT、DELETE在这里设置
timeout:5000, //超时时间
dataType:'json',
data:{id:data.id},
//返回的数据格式:json/xml/html/script/jsonp/text
success:function(res){ //成功的回调函数
if (res.code==200){
tableIns.reload({
where:"",
});
layer.msg(res.msg);
}
},
})
layer.close(index);
});
}
//批量删除
function batchDelete() {
//得到选中行
var checkStatus = table.checkStatus('goodsTable');
var dataLength = checkStatus.data.length;
if (dataLength>0){
layer.confirm('你确定要删除这些数据吗?',{icon: 3,title: '提示'},function (index) {
//获取选中行数据
var data = checkStatus.data;
var ids = "";
$.each(data,function (index, item) {
if (index==0){
ids+="ids="+item.id;
}else {
ids+="&ids="+item.id;
}
});
$.post("/goods/batchDeletegoods",ids,function (res) {
if (res.code==200){
//重新刷新表格
tableIns.reload({
where:"",
});
}
layer.msg(res.msg);
});
layer.close(index);
});
}else {
layer.msg("请选中操作行")
}
}
});
</script>
</body>
</html>
···