0、添加依赖
<!-- 添加thymeleaf依赖 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<!-- 添加thymeleaf依赖 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
1、在application.properties文件中进行静态资源配置以及配置上传文件大小
######################################################## ###server ######################################################## server.port = 8081 server.context-path=/springboot #server.address= # bind to a specific NIC #server.session-timeout= # session timeout in seconds #the context path, defaults to '/' #server.context-path=/spring-boot #server.servlet-path= # the servlet path, defaults to '/' #server.tomcat.access-log-pattern= # log pattern of the access log #server.tomcat.access-log-enabled=false # is access logging enabled #server.tomcat.protocol-header=x-forwarded-proto # ssl forward headers #server.tomcat.remote-ip-header=x-forwarded-for #server.tomcat.basedir=/tmp # base dir (usually not needed, defaults to tmp) #server.tomcat.background-processor-delay=30; # in seconds #server.tomcat.max-threads = 0 # number of threads in protocol handler #server.tomcat.uri-encoding = UTF-8 # character encoding to use for URL decoding web.upload-path=F:/resource/ spring.mvc.static-path-pattern=/** spring.resources.static-locations=classpath:/META-INF/resources/,classpath:/resources/,\ classpath:/static/,classpath:/public/,file:${web.upload-path} ######################################################## ###THYMELEAF (ThymeleafAutoConfiguration) ######################################################## spring.thymeleaf.prefix=classpath:/templates/ spring.thymeleaf.suffix=.html spring.thymeleaf.mode=HTML5 spring.thymeleaf.encoding=UTF-8 # ;charset=<encoding> is added spring.thymeleaf.content-type=text/html # set to false for hot refresh #\u5f00\u53d1\u8fc7\u7a0b\u5efa\u8bae\u5173\u95ed\u7f13\u5b58. spring.thymeleaf.cache=false ######################################################## ###file size ######################################################## multipart.maxFileSize = 10Mb multipart.maxRequestSize=100Mb ###datasource ######################################################## spring.datasource.url = jdbc:mysql://localhost:3306/test spring.datasource.username = root spring.datasource.password = 123456 spring.datasource.driverClassName = com.mysql.jdbc.Driver spring.datasource.max-active=20 spring.datasource.max-idle=8 spring.datasource.min-idle=8 spring.datasource.initial-size=10 ######################################################## ### Java Persistence Api ######################################################## # Specify the DBMS spring.jpa.database = MYSQL # Show or not log for each sql query spring.jpa.show-sql = true # Hibernate ddl auto (create, create-drop, update) spring.jpa.hibernate.ddl-auto = update # Naming strategy #[org.hibernate.cfg.ImprovedNamingStrategy #org.hibernate.cfg.DefaultNamingStrategy] spring.jpa.hibernate.naming-strategy = org.hibernate.cfg.ImprovedNamingStrategy # stripped before adding them to the entity manager) spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.MySQL5Dialect
web.upload-path=F:/resource/ spring.mvc.static-path-pattern=/** spring.resources.static-locations=classpath:/META-INF/resources/,classpath:/resources/,\ classpath:/static/,classpath:/public/,file:${web.upload-path} ######################################################## ###THYMELEAF (ThymeleafAutoConfiguration) ######################################################## spring.thymeleaf.prefix=classpath:/templates/ spring.thymeleaf.suffix=.html spring.thymeleaf.mode=HTML5 spring.thymeleaf.encoding=UTF-8 # ;charset=<encoding> is added spring.thymeleaf.content-type=text/html # set to false for hot refresh #\u5f00\u53d1\u8fc7\u7a0b\u5efa\u8bae\u5173\u95ed\u7f13\u5b58. spring.thymeleaf.cache=false ######################################################## ###file size ######################################################## multipart.maxFileSize = 10Mb multipart.maxRequestSize=100Mb ###datasource ######################################################## spring.datasource.url = jdbc:mysql://localhost:3306/test spring.datasource.username = root spring.datasource.password = 123456 spring.datasource.driverClassName = com.mysql.jdbc.Driver spring.datasource.max-active=20 spring.datasource.max-idle=8 spring.datasource.min-idle=8 spring.datasource.initial-size=10 ######################################################## ### Java Persistence Api ######################################################## # Specify the DBMS spring.jpa.database = MYSQL # Show or not log for each sql query spring.jpa.show-sql = true # Hibernate ddl auto (create, create-drop, update) spring.jpa.hibernate.ddl-auto = update # Naming strategy #[org.hibernate.cfg.ImprovedNamingStrategy #org.hibernate.cfg.DefaultNamingStrategy] spring.jpa.hibernate.naming-strategy = org.hibernate.cfg.ImprovedNamingStrategy # stripped before adding them to the entity manager) spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.MySQL5Dialect
具体详见:静态资源配置
2、导入:jquery.1.7.2.min.js、jquery-form.js文件存放在resources->static->js中,没有创建。
3、编写html文件:
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org"
xmlns:sec="http://www.thymeleaf.org/thymeleaf-extras-springsecurity3">
<head>
<title>Hello World!</title>
<script type="text/javascript" src="/springboot/js/jquery.1.7.2.min.js"></script>
<script type="text/javascript" src="/springboot/js/jquery-form.js"></script>
</head>
<body>
<table>
<tr>
<td id="imgDiv">
<img id="imgid" th:src="@{/default.jpg}" style="width:137px; height:127px"/>
</td>
</tr>
</table>
<form id="upload" enctype="multipart/form-data" method="post"><p style='color:red;text-align:left;'>
注:<br/>1.照片的像素为160*180px。<br/>2.照片格式为BMP/JPG/JPEG。<br/>3.建议照片大小不超过40k。</p>
<input type="file" name="file" id="uploadimage"/><br/>
<input type="button" value="上传" id="btn" style="width:137px; height:27px"/>
</form>
<script type="text/javascript">
$(document).ready(function() {
$("#btn").click(function () {
if(confirm("确认上传?")){
var imagePath = $("#uploadimage").val();
if (imagePath == "") {
alert("please upload image file",2);
return false;
}
var strExtension = imagePath.substr(imagePath.lastIndexOf('.') + 1);
if (strExtension!='jpg') {
if (strExtension!='bmp') {
if (strExtension!='png') {
alert("please upload file that is a image",2);
return false;
}
}
}
$("#upload").ajaxSubmit({
type : 'POST',
url : 'uploadImage',
success : function(result) {
if(result.state=='0'){
$("#imgDiv").empty();
$("#imgDiv").html('<img src="'+result.data+'" style="width:137px;height:127px;"/>');
$("#imgDiv").show();
$("#uploadimage").val("");
}else{
alert(result.msg+":"+result.data);
}
},
error : function() {
alert("上传失败,请检查网络后重试,上传文件太大");
}
});
}
})
});
</script>
</body>
</html>
4、编写控制层代码
package springboot.springbootstudy;
import java.io.IOException;
import javax.annotation.Resource;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
@Controller
@RequestMapping("/uploadImageController")
public class UploadImageController {
@Resource(name = "uploadImageService")
private UploadImageService uploadImageService;
@RequestMapping("/hello")
public String uploadImage() throws IOException {
return "hello";
}
@RequestMapping("/uploadImage")
@ResponseBody
public MessageEntity uploadImage(MessageEntity messageEntity,
@RequestParam(value = "file", required = true) MultipartFile file) throws IOException {
uploadImageService.uploadImage(messageEntity, file);
return messageEntity;
}
}
5、编写服务层代码
package springboot.springbootstudy;
import java.io.File;
import java.io.IOException;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
@Service("uploadImageService")
public class UploadImageService {
@Value("${web.upload-path}")
private String path;
@Value("${server.context-path}")
private String contxtePath;
public MessageEntity uploadImage(MessageEntity messageEntity,
@RequestParam(value = "file", required = true) MultipartFile file) throws IOException {
if (file != null) {
if (file.getName() != null || "".equals(file.getName())) {
String[] name = file.getContentType().split("/");
if ("BMP".equals(name[name.length - 1]) || "JPG".equals(name[name.length - 1])
|| "JPEG".equals(name[name.length - 1]) || "bmp".equals(name[name.length - 1])
|| "jpg".equals(name[name.length - 1]) || "jpeg".equals(name[name.length - 1])) {
// 物理地址
file.transferTo(new File(path + DateDealwith.getSHC()));
messageEntity.setState(0);
messageEntity.setMsg("上传成功!");
// 网络地址
messageEntity.setData(contxtePath + "/" + DateDealwith.getSHC());
// 先删除原来的文件,再将网络地址写入数据库
return messageEntity;
} else {
messageEntity.setState(1);
messageEntity.setMsg("格式不正确!");
}
} else {
messageEntity.setState(1);
messageEntity.setMsg("请选择文件!");
}
} else {
messageEntity.setState(1);
messageEntity.setMsg("请选择文件!");
}
return messageEntity;
}
}
6、生成文件名工具类
package springboot.springbootstudy;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
public class DateDealwith {
/**
* 获取系统当前时间
*
* @return
*/
public static Date getCurrDate() {
// 获取系统当前时间
SimpleDateFormat std = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
// 将字符串转换为Date格式
Date date = null;
try {
date = std.parse(std.format(new Date()).toString());
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// 给定格式和参数格式要统一不然就会抛出异常
return date;
}
public static String getCurrDateStr() {
// 获取系统当前时间
SimpleDateFormat std = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
// 将字符串转换为Date格式
return std.format(new Date()).toString();
// 给定格式和参数格式要统一不然就会抛出异常
}
/**
* 获取系统当前年份
*
* @return
*/
public static String getCurrYear() {
// 获取系统当前时间
SimpleDateFormat std = new SimpleDateFormat("yyyy");
// 将字符串转换为Date格式
System.out.println(std.format(new Date()).toString());
return std.format(new Date()).toString();
}
/**
* 获取两时间差
*
* @throws ParseException
*/
public static long getshijiancha(Date da) throws ParseException {
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
java.util.Date now = df.parse(df.format(new Date()).toString());
java.util.Date date = df.parse(df.format(da).toString());
long l = now.getTime() - date.getTime();
return l;
}
//生成唯一文件名
public static String getSHC() {
Date date = new Date();
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
String str = sdf.format(date);
return str;
}
}
//生成唯一文件名
public static String getSHC() {
Date date = new Date();
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
String str = sdf.format(date);
return str;
}
}