JFinal使用ajaxfileupload实现图片上传及预览
本文实例为大家分享了JFinal使用ajaxfileupload实现图片上传预览的具体代码,供大家参考,具体内容如下
1.前端jsp页面核心代码
/js/jquery.min.js"> /media/ajaxupload/ajaxfileupload.js">
<%=request.getContextPath()%>/media/file/${banner.img}"style="width:300px;height:100px;"id="imgsrc"/>
functionajaxFileUpload(fileEid,paramdata){
if(typeof(paramdata)=='undefined')paramdata={};
var$file=$('#'+fileEid).val();
if($file==''){alert("请先选择对应的上传文件,谢谢");return;}
$.ajaxFileUpload({
url:'<%=request.getContextPath()%>/banner/uploadpic',
secureuri:false,
fileElementId:fileEid,
dataType:'text',
data:paramdata,
success:function(result){
varresult=result.substring(result.indexOf("{"),result.indexOf("}")+1);
result=eval("("+result+")");
if(result.t==1){
$("#imgsrc").attr("src","<%=request.getContextPath()%>/media/file/"+result.msg);
$("#imgurl").val(result.msg);
}else{
alert("上传失败");
}
}
});
}
2.后台核心代码
publicvoiduploadpic(){
UploadFileupfile=getFile();//JFinal规定getFile()必须最先执行
Filefile=upfile.getFile();
Stringfilename=file.getName();
Stringdelfilename=filename;
if(filename!=null&&!filename.equals("")){
filename=newSimpleDateFormat("yyyyMMddkkmmss").format(newDate())+filename;
/**
*新保存的位置
*/
Stringpath=getRequest().getSession().getServletContext()
.getRealPath("/");
StringnewPath="/media/file/";//自定义目录用于存放图片
/**
*没有则新建目录
*/
Filefloder=newFile(path+newPath);
if(!floder.exists()){
floder.mkdirs();
}
/**
*保存新文件
*/
FileInputStreamfis=null;
FileOutputStreamfos=null;
try{
FilesavePath=newFile(path+newPath+filename);
if(!savePath.isDirectory())savePath.createNewFile();
fis=newFileInputStream(file);
fos=newFileOutputStream(savePath);
byte[]bt=newbyte[300];
while(fis.read(bt,0,300)!=-1){
fos.write(bt,0,300);
}
}catch(Exceptione){
e.printStackTrace();
}finally{
try{
if(null!=fis)fis.close();
if(null!=fos)fos.close();
}catch(Exceptione){
e.printStackTrace();
}
}
/**
*删除原图片,JFinal默认上传文件路径为/upload(自动创建)
*/
FiledelFile=newFile(path+"/upload/"+delfilename);
if(delFile.exists()){
delFile.delete();
}
setAttr("msg",filename);
setAttr("t",1);
}else{
setAttr("t",0);
}
renderJson();
}
附:ajaxfileupload.js代码
jQuery.extend({
createUploadIframe:function(id,uri){
//createframe
varframeId='jUploadFrame'+id;
variframeHtml=' ';
jQuery(iframeHtml).appendTo(document.body);
returnjQuery('#'+frameId).get(0);
},
createUploadForm:function(id,fileElementId,data){
//createform
varformId='jUploadForm'+id;
varfileId='jUploadFile'+id;
varform=jQuery('');
if(data){
for(variindata){
jQuery(' ').appendTo(form);
}
}
varoldElement=jQuery('#'+fileElementId);
varnewElement=jQuery(oldElement).clone();
jQuery(oldElement).attr('id',fileId);
jQuery(oldElement).before(newElement);
jQuery(oldElement).appendTo(form);
//setattributes
jQuery(form).css('position','absolute');
jQuery(form).css('top','-1200px');
jQuery(form).css('left','-1200px');
jQuery(form).appendTo('body');
returnform;
},
ajaxFileUpload:function(s){
//TODOintroduceglobalsettings,allowingtheclienttomodifythemforallrequests,notonlytimeout
s=jQuery.extend({},jQuery.ajaxSettings,s);
varid=newDate().getTime()
varform=jQuery.createUploadForm(id,s.fileElementId,(typeof(s.data)=='undefined'?false:s.data));
vario=jQuery.createUploadIframe(id,s.secureuri);
varframeId='jUploadFrame'+id;
varformId='jUploadForm'+id;
//Watchforanewsetofrequests
if(s.global&&!jQuery.active++)
{
jQuery.event.trigger("ajaxStart");
}
varrequestDone=false;
//Createtherequestobject
varxml={}
if(s.global)
jQuery.event.trigger("ajaxSend",[xml,s]);
//Waitforaresponsetocomeback
varuploadCallback=function(isTimeout)
{
vario=document.getElementById(frameId);
try{
if(io.contentWindow){
xml.responseText=io.contentWindow.document.body?io.contentWindow.document.body.innerHTML:null;
xml.responseXML=io.contentWindow.document.XMLDocument?io.contentWindow.document.XMLDocument:io.contentWindow.document;
}elseif(io.contentDocument){
xml.responseText=io.contentDocument.document.body?io.contentDocument.document.body.innerHTML:null;
xml.responseXML=io.contentDocument.document.XMLDocument?io.contentDocument.document.XMLDocument:io.contentDocument.document;
}
}catch(e){
jQuery.handleError(s,xml,null,e);
}
if(xml||isTimeout=="timeout"){
requestDone=true;
varstatus;
try{
status=isTimeout!="timeout"?"success":"error";
//Makesurethattherequestwassuccessfulornotmodified
if(status!="error"){
//processthedata(runsthexmlthroughhttpDataregardlessofcallback)
vardata=jQuery.uploadHttpData(xml,s.dataType);
//Ifalocalcallbackwasspecified,fireitandpassitthedata
if(s.success)
s.success(data,status);
//Firetheglobalcallback
if(s.global)
jQuery.event.trigger("ajaxSuccess",[xml,s]);
}else
jQuery.handleError(s,xml,status);
}catch(e){
status="error";
jQuery.handleError(s,xml,status,e);
}
//Therequestwascompleted
if(s.global)
jQuery.event.trigger("ajaxComplete",[xml,s]);
//HandletheglobalAJAXcounter
if(s.global&&!--jQuery.active)
jQuery.event.trigger("ajaxStop");
//Processresult
if(s.complete)
s.complete(xml,status);
jQuery(io).unbind()
setTimeout(function(){
try{
jQuery(io).remove();
jQuery(form).remove();
}catch(e){
jQuery.handleError(s,xml,null,e);
}
},100)
xml=null
}
}
//Timeoutchecker
if(s.timeout>0)
{
setTimeout(function(){
//Checktoseeiftherequestisstillhappening
if(!requestDone)uploadCallback("timeout");
},s.timeout);
}
try
{
varform=jQuery('#'+formId);
jQuery(form).attr('action',s.url);
jQuery(form).attr('method','POST');
jQuery(form).attr('target',frameId);
if(form.encoding){
jQuery(form).attr('encoding','multipart/form-data');
}else{
jQuery(form).attr('enctype','multipart/form-data');
}
jQuery(form).submit();
}catch(e){
jQuery.handleError(s,xml,null,e);
}
jQuery('#'+frameId).load(uploadCallback);
return{abort:function(){}};
},
uploadHttpData:function(r,type){
vardata=!type;
data=type=="xml"||data?r.responseXML:r.responseText;
//Ifthetypeis"script",evalitinglobalcontext
if(type=="script")
jQuery.globalEval(data);
//GettheJavaScriptobject,ifJSONisused.
if(type=="json")
eval("data="+data);
//evaluatescriptswithinhtml
if(type=="html")
jQuery("").html(data).evalScripts();
returndata;
}
})
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持毛票票。
热门推荐
10 新人红包祝福语简短精辟
11 幼师给毕业祝福语简短
12 生日高考祝福语妹妹简短
13 下飞机祝福语简短英文
14 元宵发客户祝福语简短
15 爸妈金婚文案祝福语简短
16 新郎朋友红包祝福语简短
17 虎年五一祝福语大全简短
18 出阁宴祝福语姐姐简短