Jquery AJAX图片上传
首先下载ajaxfileupload.js
<script type="text/javascript" src="resource/js/ajaxfileupload.js"></script>
//html
<input type="file" hidefocus="true" size="30" id="pic" class="type-file-file" name="pic">
<input type="hidden" id="pics" >
//jquery
<script type="text/javascript">
//注意change每 点击一次
//文件选择框的onchange事件只在第一次改变时生效,以后再选择文件不会触发onchange事件
//错误代码 $('input[class="type-file-file"]').change(function(){});
$('input[class="type-file-file"]').live('change',function(){
var filepatd=$(this).val();
var extStart=filepatd.lastIndexOf(".");
var ext=filepatd.substring(extStart,filepatd.lengtd).toUpperCase();
if(ext!=".PNG"&&ext!=".GIF"&&ext!=".JPG"&&ext!=".JPEG"){
// alert("图片限于png,gif,jpeg,jpg格式");
layer.msg('图片限于png,gif,jpeg,jpg格式', {shift: 6});
$(this).attr('value','');
return false;
}else{
$.ajaxFileUpload(
{
url:'doajaxfileupload.php',
secureuri:false,
fileElementId:'pic',
dataType: 'text',
success: function(data){
if(data=='error'){
layer.msg('系统错误', {shift: 6});
return false;
}else{
$('#pics').val(data);
}
}
}
);
}
});
</script>
//php页
<?php
if ((($_FILES["pic"]["type"] == "image/gif")|| ($_FILES["pic"]["type"] == "image/jpeg")|| ($_FILES["pic"]["type"] == "image/jpg")|| ($_FILES["pic"]["type"] == "image/png")|| ($_FILES["pic"]["type"] == "image/bmp")|| ($_FILES["pic"]["type"] == "image/pjpeg"))&& ($_FILES["pic"]["size"] < 10000000)){//100KB
$extend = explode(".",$_FILES["pic"]["name"]);
$key = count($extend)-1;
$ext = ".".$extend[$key];
$newfile = time().$ext;
$dirname=date('Ymd',time());
if(!file_exists('../uploadfile/'.$dirname)){mkdir('../uploadfile/'.$dirname);}
move_uploaded_file($_FILES["pic"]["tmp_name"],"../uploadfile/".$dirname."/" . $newfile);
@unlink($_FILES['pic']);
$pics="../uploadfile/".$dirname."/" . $newfile;
echo $pics;
}else {
echo 'error';
}
?>