基于SpringBoot的图片上传
添加依赖
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>${commons.io.version}</version>
</dependency>
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>${commons.fileupload.version}</version>
</dependency>
实体类
@Data
public class BaseEntity {
/** 创建者 */
private String createBy;
/** 创建时间 */
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
private Date createTime;
/** 更新者 */
private String updateBy;
/** 更新时间 */
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
private Date updateTime;
/** 备注 */
private String remark;
public void preInsert(){
this.createBy=ShiroUtils.getLoginName();
this.createTime=new Date();
this.updateBy=ShiroUtils.getLoginName();
this.updateTime=this.createTime;
}
public void preUpdate(){
this.updateBy=ShiroUtils.getLoginName();
this.updateTime=new Date();
}
}
@Data
public class Banner extends BaseEntity {
private Long id;
private String title;
private String path;
}
controller
@Controller
@RequestMapping("/cc/picture")
public class BannerController{
@PostMapping("/upload")
@ResponseBody
public Map<String, String> upload(@RequestParam("file") MultipartFile file) {
//定义一个map集合来保存返回给前台的数据
Map<String, String> map;
//定义一个保存图片的路径
String filePath = "D:/upload/picture";
map= UploadFile.uploadPicture(file,filePath);
String filename=map.get("filename");
map.put("filePath", "/upload/picture/" + filename);
return map;
}
}
图片上传工具类
public class UploadFile {
protected static Logger logger = LoggerFactory.getLogger(UploadFile.class);
public static Map<String, String> uploadPicture(MultipartFile multipartFile,String realPath){
logger.info("图片上传开始");
Map<String, String> map=new HashMap<>();
map.put("code", "20000");
map.put("msg", "处理失败");
//判断文件是否为空
if (multipartFile.isEmpty()) {
map.put("msg", "请选择文件!");
return map;
}
int one = multipartFile.getOriginalFilename().lastIndexOf(".");
//获取图片类型
String type=multipartFile.getOriginalFilename().substring(one);
//根据时间戳创建新的图片名称
String filename ="ccPicture"+System.currentTimeMillis()+type;
//logger.info("filename :"+filename );
try {
//判断realPath是否存在,不存在则创建
File folder = new File(realPath);
if (!folder.exists()) {
folder.mkdirs();
}
File file = new File(realPath, filename);
/*//此方法放在服务器上时不能用(不知道为什么0.0),所以就用下面的方法
multipartFile.transferTo(file);*/
//服务器上、本地都可以
FileUtils.copyInputStreamToFile(multipartFile.getInputStream(), file);
//成功后替换map的code和msg,用于返给js
map.put("code", "10000");
map.put("msg", "上传成功!");
map.put("filename", filename);
} catch (IOException e) {
map.put("msg", "文件上传失败!");
return map;
}
return map;
}
}
到此后台代码结束啦
上传图片的html
<!DOCTYPE HTML>
<html lang="zh" xmlns:th="http://www.thymeleaf.org">
<meta charset="utf-8">
<!--这里引入的是一些css样式-->
<head th:include="include :: header"></head>
//“上传图像”按钮的样式,建议封装到一个css里面,然后引入即可
<style>
/*选择文件上传*/
.new-contentarea {
width: 165px;
overflow:hidden;
margin: 0 auto;
position:relative;float:left;
}
.new-contentarea label {
width:100%;
height:100%;
display:block;
}
.new-contentarea input[type=file] {
width:188px;
height:60px;
background:#333;
margin: 0 auto;
position:absolute;
right:50%;
margin-right:-94px;
top:0;
right/*\**/:0px\9;
margin-right/*\**/:0px\9;
width/*\**/:10px\9;
opacity:0;
filter:alpha(opacity=0);
z-index:2;
}
a.upload-img{
width:165px;
display: inline-block;
margin-bottom: 10px;
height:37px;
line-height: 37px;
font-size: 14px;
color: #FFFFFF;
background-color: #5bc0de;
border-radius: 3px;
text-decoration:none;
cursor:pointer;
border: 0px #fff solid;
box-shadow: 0px 0px 5px #B0B0B0;
}
a.upload-img:hover{
background-color: #bce8f1;
}
.tc{text-align:center;}
</style>
<body class="white-bg">
<div class="wrapper wrapper-content animated fadeInRight ibox-content">
<form class="form-horizontal m" id="form-banner-add">
<div class="form-group">
<label class="col-sm-3 control-label">标题:</label>
<div class="col-sm-8">
<input id="title" name="title" class="form-control" type="text"/>
</div>
</div>
<div class="form-group">
<label class="col-sm-3 control-label">图片:</label>
<div class="col-sm-8">
<div class="input-group" style="width: 100%;">
<input type="hidden" name="path" id="path">
<div class="new-contentarea tc" style="width: 100%">
<a href="javascript:void(0)" class="upload-img" style="float: left;">
<label for="fileup">上传图像</label>
</a>
<input type="file" id="fileup" name="fileup" accept="image/gif,image/jpeg,image/jpg,image/png,image/svg">
<label id="fileup-error" class="error" for="fileup" style="top: 10px;"></label>
</div>
<img id="view" style="height: 200px;width: 400px;display: none;"/>
</div>
</div>
</div>
<div class="form-group">
<label class="col-sm-3 control-label">备注:</label>
<div class="col-sm-8">
<textarea id="remark" name="remark" class="form-control"></textarea>
</div>
</div>
<div class="form-group">
<div class="form-control-static col-sm-offset-9">
<button type="submit" class="btn btn-primary" id="button">提交</button>
<button onclick="$.modal.close()" class="btn btn-danger" type="button">关闭</button>
</div>
</div>
</form>
</div>
<div class="wrapper wrapper-content animated fadeInRight ibox-content"></div>
<!--这里引入的是一些js-->
<div th:include="include::footer"></div>
<script type="text/javascript">
//请求url前缀
var prefix ="/cc/picture";
var fileM = document.querySelector("#fileup");
$("#fileup").change(function () {
//获取文件对象,files是文件选取控件的属性,存储的是文件选取控件选取的文件对象,类型是一个数组
var fileObj = fileM.files[0];
//创建formdata对象,formData用来存储表单的数据,表单数据时以键值对形式存储的。
var formData = new FormData();
formData.append('file', fileObj);
var v = $(this).val();
if (v == null || v == undefined || v == "") {
$('#view').css("display", "none");
}else{
//ajax请求后台controller
var config = {
url: prefix + "/upload",
type: "post",
dataType: "json",
data : formData,
async : false,
cache : false,
contentType : false,
processData : false,
success: function (result) {
console.log(result);
//根据返回的map来进行处理
if(result.code=="10000"){
$("#view").css("display", "");
$('#view').attr("src", result.filePath);
$("#path").val(result.filePath);
}else{
//进行弹窗提醒或者不做处理也可
}
}
};
$.ajax(config)
}
});
$("#form-banner-add").validate({
rules: {
title: {
required: true
},
fileup: {
required: true
}
},
submitHandler: function (form) {
/*以下内容可以写一个通用的JS*/
var config = {
url: prefix + "/add",
type: "post",
dataType: "json",
data: $('#form-banner-add').serialize(),
success: function (result) {
//做一些弹窗提示
}
};
$.ajax(config)
}
});
</script>
</body>
</html>
图片上传结束,谢谢支持!!!