在做网站后台管理时,涉及到了图片的上传,经过多次改动后,上传图片的一系列步骤如下
1.在点击浏览按钮时弹出框只出现图片格式的文件,可在input type=file中通过accept=".jpg,.png,.jpeg" 限制。
增加限制前:
增加限制后:
但在上图标红处选择所有文件时又会出现不是图片的文件,因此进行第二步,在js中再增加判断
2.在js中判断上传的文件是否是图片
3.判断上传图片像素是否符合要求
4.可预览图片
5.表单确定后将图片保存到服务器,将图路径保存到数据库表
jsp
上传图片时要记得在form表单中增加 enctype=“multipart/form-data”, 修改input type=file的样式,参考了网上的一些方法
1、重写一个新的样式
2、将input type=file的默认样式设置display:none;,即设为不可见
3、在js里调用:当点击新样式的时候,调用这个input的点击事件
<style type="text/css">
.file-box{ position:relative;width:340px;margin:20px;}
.txt{height:22px;line-height:28px; border:1px solid #cdcdcd; width:195px;}
.btn{width:50px; color:#fff;background-color:#808da5; border:0 none;height:22px; line-height:16px!important;cursor:pointer;}
.removeBtn{width:50px; color:#fff;background-color:#d23248; border:0 none;height:22px; line-height:16px!important;cursor:pointer;}
.btn:hover{background-color:#babfca;color:#fff;}
.removeBtn:hover{background-color:#e47685;color:#fff;}
.hide{ display: none;}
.viewImg{padding:0px 122px;}
</style>
<form id="fm" method="post" novalidate enctype="multipart/form-data">
<div class="fitem">
<label>pc端图片</label>
<input type="text" id="picturePc" name="picturePc" class="txt" readonly="readonly"/>
<input type="button" class="btn" id="pcBtn" value="浏览..." />
<input type="file" name="pcFile" class="hide" id="pcFile" accept=".jpg,.png,.jpeg"/>
<input type="button" class="removeBtn" id="remove" value="移除" style="display:none" onclick="pRemove()">
<br/><font id="pcSize"></font><br/>
<div class="viewImg" id="pcView" >
<a href="" target="_blank" id="aPreview" >
<img id="preview" src="" style="height:100px;">
</a>
</div>
</div>
</form>
js
//点击浏览按钮就调用input=file这个点击事件
$('#pcBtn').click(function(){
$('#pcFile').click();
});
//检查是否是图片、限制上传像素、实现上传前预览
function pFile(file){
document.getElementById('pictureUrl').value=file.name;//获取图片名字到input框
var filePath = $('#pictureUrl').val(); //获取到input的value,里面是文件名
var fileFormat = filePath.substring(filePath.lastIndexOf(".")).toLowerCase();//获取文件类型
// 检查是否是图片
if( !fileFormat.match(/.png|.jpg|.jpeg/)) {
$.messager.alert("提示",'上传错误,文件格式必须为:png/jpg/jpeg');
$('#pictureUrl').val("");
return ;
}
if(filePath!=null){
var filePic = file; //1.读取文件详细信息
var reader = new FileReader(); //2.使用FileReader读取文件信息
reader.onload = function(e) { //4.监听读取文件过程方法,异步过程
var data = e.target.result;//e.target == this
//加载图片获取图片真实宽度和高度
var image = new Image();
image.function(){
var width= image.width;
var height= image.height;
if (width == 1920 | height ==486){
var current_pic=filePic;//获取图片数据对象
previewPic(current_pic);//调用previewPic方法来预览图片
$('#pcView').attr("style","display:inline");//显示预览框
$('#pcBtn').attr("value","更改");//将浏览按钮改为更改
$('#remove').attr("style","display:inline");//显示移除框
}else {
$.messager.alert("提示","文件尺寸应为:1920*486!");
pRemove();
return false;
}
};
image.src= data;//将解析的base64字符串赋值给img标签
};
reader.readAsDataURL(filePic); //3.开始读取
}
}
//预览pc图片
function previewPic(pic){
var r =new FileReader();
r.readAsDataURL(pic);//FileReader对象的readAsDataURL方法,把图片数据转成base64字符串数据
r.function(event){
var e = event || window.event
var img = document.getElementById("preview");
img.src = this.result;
var aImg=document.getElementById("aPreview");
aImg.href=this.result;
$("#pcSize").attr("style","display:none");//移除尺寸提示
}
}
//pc图片移除
function pRemove(){
$('#pictureUrl').val("");
$("#pcSize").attr("style","display:inline");//尺寸提示
$("#pcView").attr("style","display:none");//隐藏预览框
$("#pcBtn").attr("value","浏览...");//将更改按钮改为浏览
$("#remove").attr("style","display:none");//移除按钮隐藏
}
controller层
//添加
@RequestMapping(value = {"/addModel"}, method = RequestMethod.POST)
@ResponseBody
public String addModel(HttpServletRequest request, WebModel webModel,@RequestParam("pcFile") MultipartFile pcFile) throws Exception {
String result = "ok";
try {
//获得物理路径webapp所在路径
String pathRoot = request.getSession().getServletContext().getRealPath("");
String path="";
if(!pcFile.isEmpty()){
//生成uuid作为文件名称
String uuid = UUID.randomUUID().toString().replaceAll("-","");
//获得文件类型(可以判断如果不是图片,禁止上传)
String contentType=pcFile.getContentType();
//获得文件后缀名称
String imageName=contentType.substring(contentType.indexOf("/")+1);
path="/resources/website/images/"+uuid+"."+imageName;
pcFile.transferTo(new File(pathRoot+path));
webModel.setPictureUrl(path);
}
this.webService.addWeb(webModel);
this.logService.addSuccessLog("成功添加:" +webModel.getName(), super.getSessionUser(request));
} catch (Exception e) {
result = "error";
this.logger.error("添加发生错误:" + e.getMessage());
this.logService.addErrorLog("添加发生错误:" + e.getMessage(), getSessionUser(request));
e.printStackTrace();
}
return result;
}
最终效果如下:
点击浏览后选择文件
另:图片未上传到服务器的不能在新页面查看原图,而已经上传的回显时点击则可以查看,但我又不想一点击浏览确定后就上传图片到服务器,因为一直更换图片时容易造成图片积压太多,目前还没找到好的解决办法。