SpringMVC实现图片上传
SpringMVC与layui搭配实现图片上传(根据日期创建对应文件夹,配置虚拟目录,压缩上传,浏览器版本兼容)
前端代码
html页面
<div class="cardid-pos-con">
<img class="layui-upload-img" src="" id="cardFrontImg" height="234px" width="382px" style="display: none">
<input type="hidden" id="cardFrontPicture" >
<div id="Front">
<i id="cardFrontPic" name="cardFrontPic"></i>
<p>(身份证正面)</p>
<p id="cardFrontText"></p>
</div>
</div>
js代码:
这里用的layui上传控件!仅供参考
layui上传控件参考网址:http://www.layui.com/demo/upload.html
<script type="text/javascript" src="${ctx}/res/skin/default/js/jquery-1.8.3.min.js"></script>
<script src="${ctx}/layui/layui.js" type="text/javascript" charset="utf-8"></script>
<script src="${ctx}/layer/layer.js" type="text/javascript" charset="utf-8"></script>
<link rel="stylesheet" type="text/css" href="${ctx}/layer/theme/default/layer.css"/>
<link rel="stylesheet" type="text/css" href="${ctx}/layui/css/layui.css"/>
<script type="text/javascript">
$(function() {
/**
* layui图片上传控件
*/
layui.use(['upload','form', 'layer'], function() {
var $ = layui.jquery
, upload = layui.upload;
var ieVersion = IEVersion();
//上传身份证正面
upload.render({
elem: '#cardFrontPic'//表示当点这个id时,会触发上传控件,选择图片
, url: '${ctx}/userInfoApply/upload'
, exts: 'jpg|png|jpeg' //表示允许上传的图片格式
, before: function (obj) {
//预读本地文件示例,不支持ie8
//获取浏览器版本号判断ie版本,增强兼容
console.log(ieVersion);
if(ieVersion >= 10 ){
obj.preview(function (index, file, result) {
// console.log("版本大于10或不是ie浏览器");
// 这时的filename不是 importFile 框中的值
$('#Front').attr('style','display:none');
$('#cardFrontImg').attr('style','display:block').attr('src', result); //图片链接(base64)
});
}
}
, done: function (res) {
//如果上传失败
if (res.code > 0) {
$('#cardFrontImg').attr('style','display:none');
$('#Front').attr('style','display:block');
return layer.msg('上传的图片不能大于10M',{icon: 0});
}else{
//上传成功
//如果ie版本在10以下,则使用服务器图片地址回显
if(ieVersion < 10 || ieVersion =="edge"){
//console.log("ie版本小于10");
$('#Front').attr('style','display:none');
$('#cardFrontImg').attr('style','display:block').attr('src',"${ctx}/"+res.data.src);
}
$('#cardFrontPicture').val(res.data.src);
layer.msg("图片上传成功",{icon:1});
}
}
});
});
});
//获取浏览器版本
function IEVersion() {
var userAgent = navigator.userAgent; //取得浏览器的userAgent字符串
var isIE = userAgent.indexOf("compatible") > -1 && userAgent.indexOf("MSIE") > -1; //判断是否IE<11浏览器
var isEdge = userAgent.indexOf("Edge") > -1 && !isIE; //判断是否IE的Edge浏览器
var isIE11 = userAgent.indexOf('Trident') > -1 && userAgent.indexOf("rv:11.0") > -1;
if(isIE) {
var reIE = new RegExp("MSIE (\\d+\\.\\d+);");
reIE.test(userAgent);
var fIEVersion = parseFloat(RegExp["$1"]);
if(fIEVersion == 7) {
return 7;
} else if(fIEVersion == 8) {
return 8;
} else if(fIEVersion == 9) {
return 9;
} else if(fIEVersion == 10) {
return 10;
} else {
return 6;//IE版本<=7
}
} else if(isEdge) {
return 'edge';//edge
} else if(isIE11) {
return 11; //IE11
}else{
return 20;//不是ie浏览器
}
}
</script>
后台代码
/**
* 图片上传
* @author 王永圣
* @throws Exception
* @return str
*/
@RequestMapping(value = "/upload",method = RequestMethod.POST)
public @ResponseBody String fileUpload(@RequestParam("file") MultipartFile file,
HttpServletRequest request){
String str="";
try {
if (null != file) {
//获得当前项目物理路径webapp所在路径(本代码中未用到这个变量)
String pathRoot = request.getSession().getServletContext().getRealPath("");
//生成uuid作为文件名称
String uuid = UUID.randomUUID().toString().replaceAll("-","");
//获得文件类型(可以判断如果不是图片,禁止上传)
String contentType=file.getContentType();
//获得文件后缀名称
String imageName=contentType.substring(contentType.indexOf("/")+1);
//获取新文件存放位置
//我本地IDEA配置的虚拟目录:uploadimage.path=/Users/yswKnight/Desktop/image/
//具体用不同的开发工具配置虚拟目录,详情请看:https://blog.csdn.net/yswknight/article/details/79700193
ReadProperties rp = new ReadProperties("/ApplicationResources.properties");
String filePath= (String) rp.getProperty("uploadimage.path");
//根据日期来创建对应文件夹
String datePath=new SimpleDateFormat("yyyy/MM/dd/").format(new Date());
String path=filePath+datePath;
//如果不存在,创建文件夹
File f = new File(path);
if(!f.exists()){
f.mkdirs();
}
//新生成的文件名称
String fileName=uuid+"."+imageName;
String pathName = path+fileName;
//若照片大于10兆,禁止上传
if (file.getSize() >= 10*1024*1024){
str = "{\"code\": 1,\"msg\": \"文件不能大于10M\"}";
return str;
}else if(file.getSize() >= 1*1024*1024) {
//若图片大于1兆,小于10兆,对其进行压缩上传
//1、先保存原文件
file.transferTo(new File(pathName));
//图片尺寸不变,压缩图片文件大小outputQuality实现,参数1为最高质量
//压缩图片参考网址:https://www.cnblogs.com/miskis/p/5500822.html
//下面第一个pathName=fromPic,第二个pathName=toPic,这里两者写成同样的路径和文件名,代表直接替换
//2、生成压缩后的照片,并且对上面保存的原文件照片进行覆盖
Thumbnails.of(pathName).scale(1f).outputQuality(0.25f).toFile(pathName);
}else{
//如果小于1兆,直接保存原照片
file.transferTo(new File(pathName));
}
str = "{\"code\": 0,\"msg\": \"\",\"data\": {\"src\":\"" + "pic/"+datePath+fileName + "\"}}";
System.out.println(pathName);
}else{
logger.info("文件为空");
}
} catch (IOException e) {
e.printStackTrace();
}finally {
return str;
}
}