思路:前台选择文件,发送请求给后台,使用Spring自带MultipartFile类实现文件上传到指定目录,并将文件路径+文件名存储到数据库,页面使用时用Controller返回的数据渲染。
原来的思路:直接存储图片到数据库,结果,吃力不讨好。
环境:SpringBoot Thymeleaf BootStrap
实现:
html页面
<div class="modal-body">
<input type="file" id="file" name="file"></input>
</div>
js点击事件
点击某按钮发送请求上传文件
function subIcon(){
var formData = new FormData();
formData.append('file',$("#file")[0].files[0]);
debugger;
$.ajax({
type: "POST",
enctype: 'multipart/form-data',
url : "/gradesign/family/editIcon",
data : formData,
processData: false,
contentType: false ,
success : function(data){
$("#uploadModal").modal('hide');
swal({
title:"家庭头像修改成功!各处图标待网站刷新后刷新。",
showConfirmButton: false
})
window.setTimeout("window.location.href='/gradesign/familyInfo'",1500);
},
error : function(){
swal("系统错误请联系管理员!");
}
})
};
后台请求处理
/**
* 上传文件:
* 1、保存文件至项目/Tomcat路径下
* 2、文件路径保存到数据库中
*/
@ResponseBody
@RequestMapping("/editIcon")
public String familyEditIcon(@RequestParam("file") MultipartFile file,HttpServletRequest request) {
JSONObject result = new JSONObject();
if (file.isEmpty()) {
result.put("result", "文件为空");
return result.toJSONString();
}
String fileName = file.getOriginalFilename();
log.info("上传文件名为:"+fileName);
String path = "";
File folderFile = new File(".\\src\\main\\resources\\static\\familyicon");
String iconPath = null;
try {
iconPath = folderFile.getCanonicalPath();
} catch (IOException e1) {
e1.printStackTrace();
}
String randomPath = UUID.randomUUID().toString();
String filePath = iconPath+"\\"+randomPath+fileName;
File dest = new File(filePath);
log.info("上传路径为:"+path);
if (!dest.getParentFile().exists()) {
dest.getParentFile().mkdirs();
}
try {
file.transferTo(dest);
result.put("result", "文件上传成功");
//将路径保存到数据库
Map<String, String> map = new HashMap<String, String>();
map.put("iconurl", "/gradesign/familyicon/"+randomPath+fileName);
map.put("familyaccount",PrincipalFormat.currentFA());
familyService.familyEditIcon(map);
return result.toJSONString();
} catch (IllegalStateException e) {
e.printStackTrace();
}catch (IOException e) {
e.printStackTrace();
}
result.put("result", "文件上传失败");
return result.toJSONString();
}
路径可以写绝对路径也可以用以上相对路径,但是有一个问题就是,在开发中,每次修改头像后都需刷新项目内地址文件夹,然后刷新页面才可以更新图片。
头像页面渲染
返回头像显示页面controller
@RequestMapping("/familyInfo")
public String familyInfo(Model model) {
Map<String, String> map = new HashMap<String, String>();
map.put("familyAccount",PrincipalFormat.currentFA());
Family family = familyService.getFamilyByAccount(PrincipalFormat.currentFA());
if (family.getIconurl()=="" || family.getIconurl() == null) {
family.setIconurl("/gradesign/familyicon/2e3f5ccd-9c26-4be2-9bd7-5178041a369ewelcome_back.jpg");
}
model.addAttribute("family", family);
return "familyInfo";
}
family.getIconurl()方法获取头像路径,然后返回给页面渲染,即
${family.iconurl},如下:
<img id="icon" th:src="${family.iconurl}" width="170px" height="170px" οnclick="iconEdit()"></img>