前言
如何http 上传的multi-file的文件,本章节带大家快速实现简单的上传功能.(异步上传其它章节会有demo)
本章以模块springboot-11-upload为例(源码文末)
Demo构建
1.pom文件引入
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
2.上传service(业务功能)
@Service
public class UploadService {
Logger logger = LoggerFactory.getLogger(UploadService.class);
private final Path rootLocation;
@Autowired
public UploadService() {
this.rootLocation = Paths.get("D:/");
}
/**
* 存储文件
* @param file
* @return
*/
public boolean storeFile(MultipartFile file) {
try {
if (file.isEmpty()) {
logger.error("file is not null");
return false;
}
Files.copy(file.getInputStream(), this.rootLocation.resolve(file.getOriginalFilename()));
} catch (IOException e) {
logger.error("file upload error");
return false;
}
return true;
}
}
3.Controller层
@Controller
public class UploadController {
@Autowired
UploadService uploadService;
/**
* 访问首页
* @return
*/
@GetMapping("/")
public String index() {
return "upload";
}
/**
* 上传操作
* @param file
* @param redirectAttributes
* @return
*/
@PostMapping("/upload")
public String handleFileUpload(@RequestParam("file") MultipartFile file,
RedirectAttributes redirectAttributes) {
uploadService.storeFile(file);
redirectAttributes.addFlashAttribute("message",
"上传成功 " + file.getOriginalFilename() );
return "redirect:/";
}
}
4.html上传页面
<html xmlns:th="http://www.thymeleaf.org">
<body>
<div th:if="${message}">
<h2 th:text="${message}"/>
</div>
<div>
<form method="POST" enctype="multipart/form-data" action="/upload">
<table>
<tr><td>File to upload:</td><td><input type="file" name="file" /></td></tr>
<tr><td></td><td><input type="submit" value="Upload" /></td></tr>
</table>
</form>
</div>
</body>
</html>
5.配置文件applciation.yml
spring:
#视图层控制
mvc:
view:
prefix: classpath:/templates/
suffix: .html
static-path-pattern: /static/**
#thymeleaf start
thymeleaf:
mode: HTML
encoding: UTF-8
cache: false
servlet:
content-type: text/html
#开发时关闭缓存,不然没法看到实时页面
#限制文件上传大小
servlet:
multipart:
max-file-size: 1KB
max-request-size: 1KB
logging:
level:
com.*: debug
org.*: debug
如果是想要不限制文件上传的大小,那么就把multipart两个值都设置为-1
注意版本问题:
如果超过限制:(就会SizeLimitExceededException)
测试开始:
访问上传页面选择文件,并点击 upload按钮
测试结果(文件成功上传到相应的目录下)
End
案例简单,易于实现,但是我们的系统都在向前后端分离的趋势靠拢,如何异步上传的?
有机会在提供相应的案例,要是项目当中确实用到了,推荐一款插件
百度的一个产品webupload,用着还不错,集成也简单。
最后总结
临近2019,在这提前祝大家新年快乐。SpringBoot专栏也即将结束,感谢大家的一路陪伴,感谢有您。
微服务架构专栏即将开启~~~没上车的点个关注 今日头条@架构师速记
git下载:https://github.com/shinians/springboot-demos