LayUi + SpringBoot + Maven 实现图片的上传
需要的依赖包:
commons-io2.6.jar
commons-fileupload1.4.jar
Maven的pom.xml配置
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.6</version>
</dependency>
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.4</version>
</dependency>
//将以上代码粘贴到pom.xml的<dependencies></dependencies>中 等待IDEA自动下载
前台LayUi代码部分
render部分
layui.use(['upload','layer','table'], function () {
table = layui.table;
var upload = layui.upload;
var layer=layui.layer;
//上传监听
upload.render({
elem: '#test1',
url: '../../../upload',
auto:true, //自动提交 开启
dragDrop: true, //是否允许拖拽上传
tailor: true,
accept:'images', //允许上传的文件类型
size:10240, //设置文件最大可允许上传的大小,单位 KB。不支持ie8/9
field:'file', //MultipartFile file 对应,layui默认就是file,要改动则相应改动
before: function(obj){//文件上传前的回调
//预读本地文件示例,不支持ie8
obj.preview(function(index, file, result){
$("#demoText").text("");
$('#demo1').attr('src', result); //图片链接(base64)
});
},
//done 上传后的回调 详情见LayUi官方文档
done: function(res, index, upload) {
//每个图片上传结束的回调,成功的话,就把新图片的名字保存起来,作为数据提交
console.log(res.code);
if(res.code=="1"){
layer.msg("上传接口异常");
}else{
imgurls=imgurls+""+res.data.src;
$('#imgUrls').val(imgurls);
}
},
onComplete: function (response) { // 上传完成的回调方法
console.info("文件上传完成");
console.info(response);
}
});
隐藏域部分
//当前案例是公司新闻部分 图片上传区域为 虚线内
<form id="bj" class="layui-form" hidden="hidden">
<form class="layui-form">
<div class="layui-form-item">
<div class="layui-input-inline" >
<input type="hidden" name="news_id" required lay-verify="required" placeholder="请输入新闻编号" autocomplete="off" class="layui-input">
</div>
</div>
<div class="layui-form-item">
<label class="layui-form-label">新闻标题:</label>
<div class="layui-input-inline">
<input type="text" name="news_title" required lay-verify="required" placeholder="请输入新闻标题" autocomplete="off" class="layui-input">
</div>
</div>
<div class="layui-form-item">
<label class="layui-form-label">新闻描述:</label>
<div class="layui-input-inline">
<input type="text" name="news_desc" autocomplete="off" class="layui-input" placeholder="请输入新闻描述">
</div>
</div>
<div class="layui-form-item">
<label class="layui-form-label">新闻内容:</label>
<div class="layui-input-inline">
<input type="text" name="news_content" required lay-verify="required" placeholder="请输入新闻内容" autocomplete="off" class="layui-input">
</div>
</div>
------------------------------------------------------------------------------------------------
<!-- 上传图片位置 -->
<div class="layui-form-item">
<label class="layui-form-label">图片上传: </label>
<div class="layui-input-block">
<button type="button" class="layui-upload-drag" id="test1">
<p id="demoText"><i class="layui-icon"></i>点击上传,或将文件拖拽到此处</p>
<img class="layui-upload-img" id="demo1" width="100%" alt="">
</button>
</div>
</div>
<!-- 隐藏域 隐藏图片路径 -->
<input type="hidden" id="imgUrls" name="img_url" class="layui-input">
------------------------------------------------------------------------------------------------
<div class="layui-form-item">
<label class="layui-form-label">阅读次数:</label>
<div class="layui-input-inline">
<input type="text" name="news_num" required lay-verify="required" placeholder="请输入阅读次数" autocomplete="off" class="layui-input">
</div>
</div>
<div class="layui-form-item">
<label class="layui-form-label">发布时间:</label>
<div class="layui-input-inline">
<input type="text" name="news_date" required lay-verify="required" placeholder="请输入发布时间" autocomplete="off" class="layui-input">
</div>
</div>
</form>
</form>
Layer弹出层清空方法(这样可以清楚上次显示的图片)
layer.close(ulayer); //ulayer是弹出层的名称
location.reload();
后台部分
Controller层
/*以下是文件上传部分 在提交全部弹框信息之前就应该将图片上传到服务器 然后将存储后的路径返回给前台 前台点击提交 将图片的存储路径保存*/
@SuppressWarnings("deprecation")
@RequestMapping("/upload")
@ResponseBody
public ImgResult uplpad(MultipartFile file, HttpServletRequest request) {
System.out.println(file.getOriginalFilename());
String desFilePath = ""; //图片保存路径
String oriName = ""; //原文件名
ImgResult result = new ImgResult();
Map<String, String> dataMap = new HashMap<>();
ImgResult imgResult = new ImgResult();
try {
// 1.获取原文件名
oriName = file.getOriginalFilename();
// 2.获取原文件图片后缀,以最后的.作为截取(.jpg)
String extName = oriName.substring(oriName.lastIndexOf("."));
// 3.生成自定义的新文件名,这里以UUID.jpg|png|xxx作为格式(可选操作,也可以不自定义新文件名)
String uuid = UUID.randomUUID().toString();
String newName = uuid + extName;
// 4.获取要保存的路径文件夹
String realPath = "E:\\estart\\src\\main\\resources\\static\\uploadImges";
// 5.保存图片
desFilePath = realPath + "\\" + newName; //保存路径
File desFile = new File(desFilePath); //创建文件
file.transferTo(desFile);
// 6.返回保存结果信息
result.setCode(0); //保存状态码 成功 0 失败 1
dataMap = new HashMap<>();
dataMap.put("src", "static/uploadImges/" + newName); //保存真实路径
result.setData(dataMap); //保存信息
result.setMsg(oriName + "上传成功!"); //返回提示信息
return result;
} catch (IllegalStateException e) {
imgResult.setCode(1);
System.out.println(desFilePath + "图片保存失败");
return imgResult;
} catch (IOException e) {
imgResult.setCode(1);
System.out.println(desFilePath + "图片保存失败--IO异常");
return imgResult;
}
}
依赖的基本类(Pojo层)
package com.ftg.estart.pojo;
import java.util.Map;
public class ImgResult {
private Integer code; //图片的保存状态信息(成功或者失败)
private String msg; //要传回给前台的提示信息
private Map<String, String> data;//这里存的是图片路径等信息
private Integer totalCount=0; //这里作为后期要做多图片上传的总数的记录
private Integer successCount=0; //这里作为后期要做多图片上传的成功总数的记录
private Integer failCount=0; //这里作为后期要做多图片上传的失败总数的记录
public ImgResult() {
}
public ImgResult(Integer code, String msg, Map<String, String> data) {
this.code = code;
this.msg = msg;
this.data = data;
}
public Integer getCode() {
return code;
}
public void setCode(Integer code) {
this.code = code;
}
public String getMsg() {
return msg;
}
public void setMsg(String msg) {
this.msg = msg;
}
public Map<String, String> getData() {
return data;
}
public void setData(Map<String, String> data) {
this.data = data;
}
public Integer getTotalCount() {
return totalCount;
}
public void setTotalCount(Integer totalCount) {
this.totalCount = totalCount;
}
public Integer getSuccessCount() {
return successCount;
}
public void setSuccessCount(Integer successCount) {
this.successCount = successCount;
}
public Integer getFailCount() {
return failCount;
}
public void setFailCount(Integer failCount) {
this.failCount = failCount;
}
}