jQuery AjaxUpload 上传图片代码
本次使用AJAXUPLOAD做为上传客户端无刷上传插件,其最新版本为3.9,官方地址:http://valums.com/ajax-upload/
在页面中引入jquery.min.1.4.2.js和ajaxupload.js
<scriptsrc="Scripts/jquery-1.4.2.min.js"type="text/javascript"></script> <scriptsrc="Scripts/ajaxupload3.9.js"type="text/javascript"></script>
HTML代码:
<styletype="text/css">
#txtFileName{
width:300px;
}
.btnsubmit{border-bottom:#cc4f001pxsolid;border-left:#ff90001pxsolid;border-top:#ff90001pxsolid;border-right:#cc4f001pxsolid;text-align:center;padding:2px10px;line-height:16px;background:#e36b0f;height:24px;color:#fff;font-size:12px;cursor:pointer;}
</style>
上传图片:<inputtype="text"id="txtFileName"/><divid="btnUp"style="width:300px;"class=btnsubmit>浏览</div>
<divid="imglist"></div>
js代码:
<scripttype="text/javascript">
$(function(){
varbutton=$('#btnUp'),interval;
newAjaxUpload(button,{
//action:'upload-test.php',文件上传服务器端执行的地址
action:'/handler/AjaxuploadHandler.ashx',
name:'myfile',
onSubmit:function(file,ext){
if(!(ext&&/^(jpg|jpeg|JPG|JPEG)$/.test(ext))){
alert('图片格式不正确,请选择jpg格式的文件!','系统提示');
returnfalse;
}
//changebuttontext,whenuserselectsfile
button.text('上传中');
//Ifyouwanttoallowuploadingonly1fileattime,
//youcandisableuploadbutton
this.disable();
//Uploding->Uploading.->Uploading...
interval=window.setInterval(function(){
vartext=button.text();
if(text.length<10){
button.text(text+'|');
}else{
button.text('上传中');
}
},200);
},
onComplete:function(file,response){
//file本地文件名称,response服务器端传回的信息
button.text('上传图片(只允许上传JPG格式的图片,大小不得大于150K)');
window.clearInterval(interval);
//enableuploadbutton
this.enable();
vark=response.replace("<PRE>","").replace("</PRE>","");
if(k=='-1'){
alert('您上传的文件太大啦!请不要超过150K');
}
else{
alert("服务器端传回的串:"+k);
alert("本地文件名称:"+file);
$("#txtFileName").val(k);
$("<img/>").appendTo($('#imglist')).attr("src",k);
}
}
});
});
</script>
服务器端ajaxuploadhandler.ashx代码
publicvoidProcessRequest(HttpContextcontext)
{
context.Response.ContentType="text/plain";
HttpPostedFilepostedFile=context.Request.Files[0];
stringsavePath="/upload/images/";
intfilelength=postedFile.ContentLength;
intfileSize=163600;//150K
stringfileName="-1";//返回的上传后的文件名
if(filelength<=fileSize)
{
byte[]buffer=newbyte[filelength];
postedFile.InputStream.Read(buffer,0,filelength);
fileName=UploadImage(buffer,savePath,"jpg");
}
context.Response.Write(fileName);
}
publicstaticstringUploadImage(byte[]imgBuffer,stringuploadpath,stringext)
{
try
{
System.IO.MemoryStreamm=newMemoryStream(imgBuffer);
if(!Directory.Exists(HttpContext.Current.Server.MapPath(uploadpath)))
Directory.CreateDirectory(HttpContext.Current.Server.MapPath(uploadpath));
stringimgname=CreateIDCode()+"."+ext;
string_path=HttpContext.Current.Server.MapPath(uploadpath)+imgname;
Imageimg=Image.FromStream(m);
if(ext=="jpg")
img.Save(_path,System.Drawing.Imaging.ImageFormat.Jpeg);
else
img.Save(_path,System.Drawing.Imaging.ImageFormat.Gif);
m.Close();
returnuploadpath+imgname;
}
catch(Exceptionex)
{
returnex.Message;
}
}
publicstaticstringCreateIDCode()
{
DateTimeTime1=DateTime.Now.ToUniversalTime();
DateTimeTime2=Convert.ToDateTime("1970-01-01");
TimeSpanspan=Time1-Time2;//span就是两个日期之间的差额
stringt=span.TotalMilliseconds.ToString("0");
returnt;
}
在PHP网站开发中,文件上传功能时常用到,之前我已介绍过如何利用PHP实现文件上传功能。随着WEB技术的发展,用户体验成为衡量网站成功与否的关键,今天和大家分享如何在PHP中利用Jquery实现Ajax方式文件上传功能的例子,其中使用到了Jquery插件Ajaxupload,其可以实现单个文件和多文件上传功能。
AjaxUpload
Jquery插件AjaxUpload实现文件上传功能时无需创建form表单,即可实现Ajax方式的文件上传,当然根据需要也可以创建form表单。
准备工作
1、下载Jquery开发包和文件上传插件AjaxUpload。
2、创建uploadfile.html,并引入Jquery开发包和AjaxUpload插件
<scriptsrc="js/jquery-1.3.js"></script> <scriptsrc="js/ajaxupload.3.5.js"></script>
3、根据Jquery插件AjaxUpload的需要,创建一个触发Ajax文件上传功能的DIV
<ul> <liid="example"> <divid="upload_button">文件上传</div> <p>已上传的文件列表:</p> <olclass="files"></ol> </ul>
注释:由下面的代码我们可以看到Jquery插件AjaxUpload是根据upload_button这个DIV触发文件上传功能。
前台JS代码
在代码中我设置了开关,根据需要可以匹配上传文件类型,同时也可以设置是以Ajax方式实现单个文件上传还是多个文件上传。
$(document).ready(function(){
varbutton=$('#upload_button'),interval;
varfileType="all",fileNum="one";
newAjaxUpload(button,{
action:'do/uploadfile.php',
/*data:{
'buttoninfo':button.text()
},*/
name:'userfile',
onSubmit:function(file,ext){
if(fileType=="pic")
{
if(ext&&/^(jpg|png|jpeg|gif)$/.test(ext)){
this.setData({
'info':'文件类型为图片'
});
}else{
$('<li></li>').appendTo('#example.files').text('非图片类型文件,请重传');
returnfalse;
}
}
button.text('文件上传中');
if(fileNum=='one')
this.disable();
interval=window.setInterval(function(){
vartext=button.text();
if(text.length<14){
button.text(text+'.');
}else{
button.text('文件上传中');
}
},200);
},
onComplete:function(file,response){
if(response!="success")
alert(response);
button.text('文件上传');
window.clearInterval(interval);
this.enable();
if(response=="success");
$('<li></li>').appendTo('#example.files').text(file);
}
});
});
注释:
第1行:$(document).ready()函数,Jquery中的函数,类似于window.load,使用这个函数可在DOM载入就绪能够读取并操纵时立即调用绑定的函数。
第3行:fileType和fileNum参数代表上传文件的类型和数量,默认值为可上传所有类型文件,同一时间只能上传一个文件,如想上传图片文件或同时上传多个文件,可将这两个变量值变为pic和more。
第6~8行:POST到服务器的数据,你可以设置静态值也可以通过Jquery的DOM操作函数获得一些动态值,比如form表单中INPUT的值等。
第9行:等同于前端
<inputtype="file"name="userfile">
服务器端$_FILES['userfile']
第10~36行:文件上传前触发的功能。
第11~21行:图片文件类型的过滤功能,JquerysetData函数用来设置POST至服务器端的值。
第25~26行:设置同时只上传一个文件还是多个文件,如果只上传一个文件,则将触发按钮禁掉。如果要多传输几个文件,请在服务器端PHP文件上传程序中设置MAXSIZE的值,当然上传文件的大小限制同时和PHP.INI文件中的设置也有关。
第28~35行:在文件上传过程中每隔200毫秒动态更新一次按钮的文字,已实现动态提示的效果。window.setInterval函数用来每隔指定的时间就执行一次内置的函数,交互时间单位为豪秒。
第37~49行:文件上传功能完成后触发的功能,根据返回值如果服务器端报错,则前端通过ALERT方式提示出错信息。
服务器端PHP文件上传代码
大体上是根据之前介绍的PHP文件上传功能代码实例教程改编,涉及到的文件上传大小的设置,出错信息等说明都已在此文中详细说明。
$upload_dir='../file/';
$file_path=$upload_dir.$_FILES['userfile']['name'];
$MAX_SIZE=20000000;
echo$_POST['buttoninfo'];
if(!is_dir($upload_dir))
{
if(!mkdir($upload_dir))
echo"文件上传目录不存在并且无法创建文件上传目录";
if(!chmod($upload_dir,0755))
echo"文件上传目录的权限无法设定为可读可写";
}
if($_FILES['userfile']['size']>$MAX_SIZE)
echo"上传的文件大小超过了规定大小";
if($_FILES['userfile']['size']==0)
echo"请选择上传的文件";
if(!move_uploaded_file($_FILES['userfile']['tmp_name'],$file_path))
echo"复制文件失败,请重新上传";
switch($_FILES['userfile']['error'])
{
case0:
echo"success";
break;
case1:
echo"上传的文件超过了php.ini中upload_max_filesize选项限制的值";
break;
case2:
echo"上传文件的大小超过了HTML表单中MAX_FILE_SIZE选项指定的值";
break;
case3:
echo"文件只有部分被上传";
break;
case4:
echo"没有文件被上传";
break;
}
总结
基本上前端Ajax文件上传触发功能和服务器端PHP文件上传功能的原型就介绍完毕了,你可以根据自身需要对前后端代码进行补充,也可以将一些功能独立出来,比如文件类型、单个文件或者多文件上传功能。总的来说Jquery插件AjaxUpload实现文件上传功能的应用还是比较容易的。