创建springboot项目,添加依赖
点击成war包
添加pom.xml依赖
<!-- 导入web组件启动器,版本随父工程 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<!-- 移除嵌入式tomcat插件 -->
<exclusions>
<exclusion>
<groupId>org.springframework.boot</groupId>
<artifactId>Spring-boot-start-tomcat</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-tomcat</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
</dependencies>
设置参数文件
spring.thymeleaf.cache=false
spring.thymeleaf.prefix=classpath:/templates/
spring.thymeleaf.suffix=.html
spring.servlet.multipart.max-file-size=500MB
spring.servlet.multipart.max-request-size=500MB
文件结构的框架图是:
设置外部tomcat,模拟真实环境(springboot内置的tomcat可能与真实环境不一致,导致部署失败)
出现Cannot resolve MVC view 'XXXX’有以下集中情况
1.没加依赖
2.依赖的版本不对
文件上传
1、测试springmvc是否能够连通
@RequestMapping("/index")
@ResponseBody
public String testIndex(){
return "test"; //返回的是字符串
}
@GetMapping("/in")
public String testhtml(){
return "test"; //返回的是页面
}
test.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<h1>测试springmvc是否搭建成功</h1>
</body>
</html>
2、编写文件上传前段代码
<!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>
<meta charset="UTF-8"/>
<title>fileUpload page</title>
</head>
<body>
<h1 th:inlines="text">文件上传</h1>
<form th:action="@{/fileUploading}" method="post" enctype="multipart/form-data">
<p>选择文件: <input type="file" name="fileName"/></p>
<p><input type="submit" value="提交"/></p>
</form>
</body>
</html>
3.编写controller
@RequestMapping(value = "/fileUploading", method = RequestMethod.POST)
@ResponseBody
public String fileUpload(@RequestParam("fileName") MultipartFile file) {
if (file.isEmpty()) {
return "this file is empty";
}
String fileName = file.getOriginalFilename();
int size = (int) file.getSize();
System.out.println(fileName + "-->" + size);
String path = "F:/test";//文件保存路径
File targetFile = new File(path + "/" + fileName);
if (!targetFile.getParentFile().exists()) { //判断文件父目录是否存在
targetFile.getParentFile().mkdir();
}
try {
file.transferTo(targetFile); //保存文件
return "upload file success";
} catch (IllegalStateException e) {
e.printStackTrace();
return "upload file fail";
} catch (IOException e) {
e.printStackTrace();
return "upload file fail";
}
}
tomacat部署运行
把war包放入tomcat中
然后点击tomcat\bin\startup.bat
部署成功之后的结果就是这样
lhttp://localhost:8080/fafaf/file
其中fafaf是项目名