JS前端
注意:ajaxFileUpload需要有jQuery的支持,所以这段JS代码需要放在引入的jQuery代码后面,或者放在$.ready(function(){})的方法里面,不然会报错
//JS图片异步上传 function ajaxIconUpload() { $.ajaxFileUpload ( { url: "${ctx}/service/iconUpload.do",//用于文件上传的服务器端请求地址 secureuri: false,//一般设置为false fileElementId: 'iconFile',//文件上传空间的id属性 <input type="file" id="file" name="file" /> dataType: 'json',//返回值类型 一般设置为json success: function (data,status) //服务器成功响应处理函数 { alert(data); $("#iconFile-queue").attr("src",data); if (typeof (data.error) != 'undefined') { if (data.error != '') { alert(data.error); } else { alert(data.msg); } } },error: function (data,status,e)//服务器响应失败处理函数 { alert(e); } } ) return false; }
HTML前端
<div class="field-Box"> <label> <span class="required_star">*</span> <YESsafe:localMessage key="service_management_icon"/> </label> <div id="div_iconFile" style="float:left;background-color:#00A232;height: 30px; line-height: 30px; width: 80px;" class="uploadify-button iconDiv" onclick="javascript:clickIconFile()" id="iconFile-button"> <span class="uploadify-button-text">选择文件</span> <input name="iconFile" style="display:none;height: 30px; width: 80px;" class="uploadify" id="iconFile" type="file" onchange="ajaxIconUpload();previewImage(this);" /> </div> <div class="uploadify-queue" id="iconFile-queue"></div> <div id="preview"></div> <!-- <div id="iconFile" ></div> --> </div> <div id="showIconDiv" class="field-Box" style="display:none"></div>
WEB服务器端
@RequestMapping(value= "/service/iconUpload",method=RequestMethod.POST) @ResponseBody public String iconUpload(HttpServletRequestrequest,@RequestParam(value ="iconFile") MultipartFile iconFile,@RequestParam(value ="sessionId",required = false) String sessionId){ AjaxResult ajaxResult = newAjaxResult(); ByteArrayOutputStream bos = newByteArrayOutputStream(); InputStream stream = null; try{ if(iconFile != null){ stream =iconFile.getInputStream(); byte[] buffer =newbyte[1024*1024]; int byteread = 0; while((byteread=stream.read(buffer))!=-1) { bos.write(buffer,byteread); bos.flush(); } if(StringUtils.isNotBlank(sessionId)){ HttpSession session =MySessionContext.getInstance().getSessionById(sessionId); if(session!=null){ session.setAttribute("serviceIconByteArray",bos.toByteArray()); session.setAttribute("serviceIconName",iconFile.getOriginalFilename()); } }else{ request.getSession().setAttribute("serviceIconByteArray",bos.toByteArray()); request.getSession().setAttribute("serviceIconName",iconFile.getOriginalFilename()); } ajaxResult.setSuccess(true); } }catch(Exception e){ logger.error("icon uploaderror-->",e); }finally{ try{ bos.close(); if(stream!=null){ stream.close(); } }catch(Exception e){ logger.error("iconupload:stream close error-->",e); } } returnJSONObject.fromObject(ajaxResult).toString(); }
另外我们经常需要用到在前端预览上传的图片
//预览图片 function previewImage(file) { var MAXWIDTH = 260; var MAXHEIGHT = 180; var div = document.getElementById('preview'); var fileSize = 0; var isIE = /msie/i.test(navigator.userAgent) && !window.opera; if (isIE && !file.files) { var filePath = file.value; var fileSystem = new ActiveXObject("Scripting.FileSystemObject"); var file = fileSystem.GetFile (filePath); fileSize = file.Size; } else { fileSize = file.files[0].size; } var size = fileSize / 1024; if(size>100){ alert("<YESsafe:localMessage key="service_management_icon_limit"/>100KB"); } else if (file.files && file.files[0]) { div.innerHTML ='<img id=imghead>'; var img = document.getElementById('imghead'); img.onload = function(){//1 var rect = clacImgZoomParam(MAXWIDTH,MAXHEIGHT,img.offsetWidth,img.offsetHeight); img.width = rect.width; img.height = rect.height; // img.style.marginLeft = rect.left+'px'; img.style.marginTop = rect.top+'px'; } var reader = new FileReader(); reader.onload = function(evt){img.src = evt.target.result;} reader.readAsDataURL(file.files[0]); iconSelectFlag= true; } else //兼容IE { var sFilter='filter:progid:DXImageTransform.Microsoft.AlphaImageLoader(sizingMethod=scale,src="'; file.select(); var src = document.selection.createRange().text; div.innerHTML = '<img id=imghead>'; var img = document.getElementById('imghead'); img.filters.item('DXImageTransform.Microsoft.AlphaImageLoader').src = src; var rect = clacImgZoomParam(MAXWIDTH,img.offsetHeight); status =('rect:'+rect.top+','+rect.left+','+rect.width+','+rect.height); div.innerHTML = "<div id=divhead style='width:"+rect.width+"px;height:"+rect.height+"px;margin-top:"+rect.top+"px;"+sFilter+src+"\"'></div>"; iconSelectFlag= true; } if(iconSelctFlag){ $("#div_iconFile").parent().children("#icon-error").remove(); } } function clacImgZoomParam( maxWidth,maxHeight,width,height ){ var param = {top:0,left:0,width:width,height:height}; if( width>maxWidth || height>maxHeight ) { rateWidth = width / maxWidth; rateHeight = height / maxHeight; if( rateWidth > rateHeight ) { param.width = maxWidth; param.height = Math.round(height / rateWidth); }else { param.width = Math.round(width / rateHeight); param.height = maxHeight; } } param.left = Math.round((maxWidth - param.width) / 2); param.top = Math.round((maxHeight - param.height) / 2); return param; } function clickIconFile(){ var ie=navigator.appName=="Microsoft Internet Explorer" ? true : false; if(ie){ document.getElementById("iconFile").click(); }else if (navigator.userAgent.indexOf('Firefox') >= 0){ var a=document.createEvent("MouseEvents");//FF的处理 a.initEvent("click",true,true); document.getElementById("iconFile").dispatchEvent(a); } else{ document.getElementById("iconFile").click(); } }
另外,我们有时候需要用到清空Input标签下的File类型的参数,有以下三种方法
清空input file
代码如下:
<inputtype="file" id="fileupload" name="file" />
第一种:
var obj =document.getElementById('fileupload') ;
obj.select();
document.selection.clear();
第二种:
var obj =document.getElementById('fileupload') ;
obj.outerHTML=obj.outerHTML;
来自 <http://www.jb51.net/article/42271.htm>
第三种
var file =document.getElementById("iconFile");
if(file.outerHTML) {
file.outerHTML = file.outerHTML;
} else { // FF(包括3.5)
file.value = "";
}
原文链接:https://www.f2er.com/ajax/163727.html