这里记录下一个完整的头像上传过程,实用部分笔者会指出,嘿嘿嘿。
工具:idea
css文件:w3.css
声明,笔者没有使用ajax来上传头像,原因是头像为单个,内容小,有需要转ajax的简单修改即可。
步骤:首先是绘制静态页面(包括修改默认上传样式),然后就是上传头像,最后反馈上传结果
这里直接给出主要html代码:
<div class="w3-container w3-white w3-round" style="margin-top: 20px;">
<div class="w3-text-grey" style="margin-top: 5px;">头像上传</div>
<hr style="margin-top: 5px"/>
<form action="${pageContext.request.contextPath}/user/upLoadImg.html" method="post" enctype="multipart/form-data" name="upload_form">
<div style="margin-left: 0px">
<table class="w3-table w3-text-dark-grey" style="font-size: 13px;">
<tr>
<td style="text-align: right;vertical-align: middle;width: 18%">预览头像</td>
<td>
<span style="display: block;width: 50px;">
<img src="${pageContext.request.contextPath}${currentUser.picUrl}" style="width: 100%;height: 50px" id="currentImg" />
</span>
</td>
</tr>
</table>
</div>
<div style="margin-left: 8.5%;margin-top: 10px">
<span class="w3-text-dark-grey" style="font-size: 13px">选择一个图片文件:</span>
<input id="choiceImg" type="button" class="w3-btn w3-teal w3-tiny" style="width: 60px" value="浏览...">
<span id="imgName" class="w3-text-dark-grey" style="font-size: 13px"></span>
<input style="display: none" id="realChoiceImg" name="file" type="file" accept="image/jpeg,image/png,image/jpg"/><br><br>
<span class="w3-text-grey" style="font-size: 13px">支持 2MB 以内的 PNG / JPG / JPEG 文件</span>
</div>
<div style="text-align: center;margin-top: 10px">
<input class="w3-btn w3-teal w3-small" style="width: 80px;" type="submit" value="上传头像">
</div>
</form>
<hr style="margin-top: 5px"/>
<div class="w3-text-dark-grey" style="font-size: 13px;margin-bottom: 10px">
<span>关于头像的规则</span><br><br>
<span><strong>· </strong>禁止使用任何低俗或者敏感图片作为头像</span><br>
<span><strong>· </strong>如果你是男,请不要用女人的照片作为头像,这样可能会对其他人产生误导</span>
</div>
</div>
<%--模态框--%>
<div id="alert_warn" class="w3-modal">
<div class="w3-modal-content w3-animate-top w3-card-8" style="width: 30%">
<header class="w3-container w3-orange" >
<span οnclick="document.getElementById('alert_warn').style.display='none'" class="w3-closebtn">×</span>
<p style="color: white">提醒</p>
</header>
<div class="w3-container" style="height: 100px;text-align: center">
<br>
<span class="" id="alert_content"></span>
</div>
</div>
</div>
下面是js代码:
<%--js--%>
<script>
$(document).ready(function () {
$("#choiceImg").click(function () {
$("#realChoiceImg").click();
$("#realChoiceImg").on('change',function(){
var filePath = $(this).val(), //获取到input的value,里面是文件的路径
fileFormat = filePath.substring(filePath.lastIndexOf(".")).toLowerCase(),
src = window.URL.createObjectURL(this.files[0]); //转成可以在本地预览的格式
// 检查是否是图片
if( !fileFormat.match(/.png|.jpg|.jpeg/) ) {
// alert('上传错误,文件格式必须为:png/jpg/jpeg');
$("#alert_warn").css("display","block");
$("#alert_content").text("上传错误,文件格式必须为:png/jpg/jpeg");
return;
}
$('#currentImg').attr('src',src);
})
// $("#imgName").text("已选择");
})
/*提示用户名重复*/
if("${flag}"==1){
$("#alert_warn").css("display","block");
$("#alert_content").text("上传成功");
}
})
</script>
关于css和js的实用部分请看对应笔录(二)的内容,这里追加说明两点:
一、修改原file上传按钮的样式,笔者的做法是:间接修改,这里通过w3.css简单生成一个相对美观的按钮(浏览...),然后隐藏起真实效果的file按钮,通过js,在点击浏览按钮后,也执行file按钮的click事件,达到间接修改的目的。
二、记录一个w3.css模态框的使用,这里笔者修改成了一个提醒效果,提醒内容可以在js内设置
整体效果如下:
然后是上传头像的java后台内容:
public String upLoadImg(MultipartFile[] files, HttpServletRequest request, HttpServletResponse response) {
response.setContentType("text/html;charset=utf-8");
HttpSession session = request.getSession();
//得到上传文件的保存目录,将上传的文件存放于WEB-INF目录下,不允许外界直接访问,保证上传文件的安全
ServletContext application = session.getServletContext();
String path="/static/images/frontstage/head_img";
String realPath = application.getRealPath(path);
File pathFile = new File(realPath);
if(!pathFile.exists()&&!pathFile.isDirectory()){
pathFile.mkdirs();
}
String finalPath="";
String flag="false";
if(files!=null&&files.length>0){
for(int i =0;i<files.length;i++){
MultipartFile file = files[i];
try {
String uuPath=Until.getUUID();
finalPath = realPath +"/"+ uuPath+"_"+file.getOriginalFilename();
file.transferTo(new File(finalPath));
String username = (String) SecurityUtils.getSubject().getPrincipal();
String savePath=path+"/"+uuPath+"_"+file.getOriginalFilename();
userDao.saveImgUrl(username,savePath);
Users user=getUser(username);
SecurityUtils.getSubject().getSession().setAttribute("currentUser",user);
flag="true";
} catch (Exception e) {
e.printStackTrace();
}
}
}
response.reset();
return flag;
}
通过name为file的input获取头像内容,使用spring框架自带的上传方法完成上传目的,同时保存上传路径。
通过flag标记上传是否成功,在页面弹出模态,完成信息反馈