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 $ = layui.jquery;
var form=layui.form;
var layer = layui.layer;
var table = layui.table;
var layedit=layui.layedit;
var upload=layui.upload;
//打開添加頁面
var mainIndex;
var type;
//初始化表格
var tableIns = table.render({
elem: "#goodsTable",
title: "日志數據表格",
url: "/good/loadAllgoods",
toolbar: "#goodsToolBar",
page: true,
height: "full-190",
cols: [ [
{field: 'id', title: 'ID', align: 'center',width:'50'},
{field: 'goodsname', title: '商品名稱', align: 'center',width:'150'},
{field: 'providername', title: '供應商', align: 'center',width:'150'},
{field: 'produceplace', title: '商品產地', align: 'center',width:'150'},
{field: 'description', title: '商品描述', align: 'center',width:'150'},
{field: 'price', title: '銷售價格', align: 'center',width:'90'},
{field: 'number', title: '數量', align: 'center',width:'90'},
{field: 'dangernum', title: '庫存預警值', align: 'center',width:'100'},
{field: 'goodsimg', title: '商品圖片', align: 'center',width:'150', templet:function(d){
return '<img width=40 height=40 src=/file/showImageByPath?path='+d.goodsimg+ ' />';
}},
{field: 'size', title: '規格', align: 'center',width:'120'},
{field: 'goodspackage', title: '包裝', align: 'center',width:'120'},
{field: 'productcode', title: '生產批號', align: 'center',width:'130'},
{field: 'available', title: '是否可用', align: 'center',width:'100',templet:function (d) {
return d.available==1?'<font color="blue">可用</font>':'<font color="red">不可用</font>';
}},
{fixed: 'right', title: '操作', toolbar: '#goodsRowBar', align: 'center',width:'180'}
] ],
done:function (data, curr, count) {
//不是第一頁時,如果當前返回的數據為0那么就返回上一頁
if(data.data.length==0&&curr!=1){
tableIns.reload({
page:{
curr:curr-1
}
})
}
}
});
//查詢可用的供應商
$.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=$("#select_providerid");
$.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>
