本章讲述:
- springboot项目实现单/多图片上传 以及解决途中
- 限制上传图片容量
- list、String的转化
- thymeleaf判断List<String>为不为空 的问题
- 前端插入background-image
效果:
实现:
0.自动创建各个用户独立的文件夹
1.上传单图片
2.上传多图片
解决问题:
a 图片容量限制
b listString转化
c thymeleaf判断列表
效果:上传一张图片:(可以做头像的)点击上传封面、选择图片、并且展示-
发布成功后:以第一张为首页
0.创建上传图片的文件夹
private String filePath = "src/main/resources/static/upload-dir";
private String realPath = "src/main/resources/static/upload-dir";
private Path rootLocation;
/**
* 创建上传图片的文件夹
* @param account_Id 用户Id 每个用户拥有单独的文件夹
*/
public void ProductionService(String account_Id) {
if(StringUtils.isBlank(account_Id)){
throw new CustomizeCodeException(ErrorCodeEnumImp.NO_LOGIN);
}
if(realPath.contains(account_Id)){
realPath=realPath;
}else{
realPath=filePath+"/"+account_Id;
}
this.rootLocation = Paths.get(realPath);
try {
Files.createDirectories(rootLocation);
} catch (IOException e) {
throw new CustomizeCodeException(ErrorCodeEnumImp.FAIL_INITSTORAGE);
}
}
1.上传并回显一张图片
前端显示
```html
<!--上传图片-->
<div class="list-content">
<div class="block">
<div class="main">
<div id="container" class="file-container">
<div class="cover">
<!--如果不需要回显图片,src留空即可-->
<img class="upload-img" th:src="@{${pic}}" th:if="${pic} != null" /><div class="cover-text">上传封面</div>
<img th:if="${pic} == null" class="upload-img-cover" th:src="@{images/download.png}"/><div class="cover-text">上传封面</div>
<img th:if="${pic} == null" class="upload-img-cover" th:src="@{/images/download.png}"/><div class="cover-text">上传封面</div>
<input type="file" class="file" name="pic" id="upload" accept="image/gif, image/jpeg, image/jpg, image/png">
<input type="hidden" name="pictext" th:value="${pictext}" />
</div>
</div>
</div>
<script>
$("#upload").change(function () {
var filePath = $(this)[0].files[0];// 获取input上传的文件
if (filePath.name) {
alter("未选择封面");
} else {
var url = window.URL.createObjectURL(filePatha); //将上传的文件转化为url
$('#container img').attr('src', url);
$('#container img').attr('class',"upload-img-cover upload-img");
}
console.log(url);
}
});
</script>
</div>
</div>
Controller获取
pictext是为了存取图片存取路径;防止如果不修改图片的话,图片路径会清空
/*新建/更新发布*/
@PostMapping("/publish")
public String doPublish(@RequestParam(value = "pic", required = false) MultipartFile pic,
@RequestParam(value = "pictext" , required = false)String pictext,
HttpServletRequest request,
Model model){
if (pic.isEmpty()&&StringUtils.isBlank(pictext)) {
model.addAttribute("error", "图片不能为空");
return "publish";
}
User user = null;
user = (User) request.getSession().getAttribute("user");
if (user == null || "".equals(user.getName())) {
model.addAttribute("error", "请先登录");
return "publish";
}
String fileName = pic.getOriginalFilename();
String suffixName = fileName.substring(fileName.lastIndexOf("."));
//fileName= "zhenbao-"+UUID.randomUUID()+suffixName;
fileName = user