Ajax上传图片
Q.1我想将这个表单转换成ajax,但是好像我的ajax代码缺less一些东西。 提交完全没有做任何事情。
Q2。 当文件被select不等待提交时,我也希望该function在更改时触发。
这是JS。
$('#imageUploadForm').on('submit',(function(e) { e.preventDefault() $.ajax({ type:'POST', url: $(this).attr('action'), data:$(this).serialize(), cache:false }); }));
和HTMl与PHP。
<form name="photo" id="imageUploadForm" enctype="multipart/form-data" action="<?php echo $_SERVER["PHP_SELF"];?>" method="post"> <input type="file" style="widows:0; height:0" id="ImageBrowse" hidden="hidden" name="image" size="30"/> <input type="submit" name="upload" value="Upload" /> <img width="100" style="border:#000; z-index:1;position: relative; border-width:2px; float:left" height="100px" src="<?php echo $upload_path.$large_image_name.$_SESSION['user_file_ext'];?>" id="thumbnail"/> </form>
首先在你的ajax调用包含成功和错误function,然后检查是否给你错误或什么?
你的代码应该是这样的
$(document).ready(function (e) { $('#imageUploadForm').on('submit',(function(e) { e.preventDefault(); var formData = new FormData(this); $.ajax({ type:'POST', url: $(this).attr('action'), data:formData, cache:false, contentType: false, processData: false, success:function(data){ console.log("success"); console.log(data); }, error: function(data){ console.log("error"); console.log(data); } }); })); $("#ImageBrowse").on("change", function() { $("#imageUploadForm").submit(); }); });
HTML代码
<div class="rCol"> <div id ="prv" style="height:auto; width:auto; float:left; margin-bottom: 28px; margin-left: 200px;"></div> </div> <div class="rCol" style="clear:both;"> <label > Upload Photo : </label> <input type="file" id="file" name='file' onChange=" return submitForm();"> <input type="hidden" id="filecount" value='0'>
这里是Ajax代码:
function submitForm() { var fcnt = $('#filecount').val(); var fname = $('#filename').val(); var imgclean = $('#file'); if(fcnt<=5) { data = new FormData(); data.append('file', $('#file')[0].files[0]); var imgname = $('input[type=file]').val(); var size = $('#file')[0].files[0].size; var ext = imgname.substr( (imgname.lastIndexOf('.') +1) ); if(ext=='jpg' || ext=='jpeg' || ext=='png' || ext=='gif' || ext=='PNG' || ext=='JPG' || ext=='JPEG') { if(size<=1000000) { $.ajax({ url: "<?php echo base_url() ?>/upload.php", type: "POST", data: data, enctype: 'multipart/form-data', processData: false, // tell jQuery not to process the data contentType: false // tell jQuery not to set contentType }).done(function(data) { if(data!='FILE_SIZE_ERROR' || data!='FILE_TYPE_ERROR' ) { fcnt = parseInt(fcnt)+1; $('#filecount').val(fcnt); var img = '<div class="dialog" id ="img_'+fcnt+'" ><img src="<?php echo base_url() ?>/local_cdn/'+data+'"><a href="#" id="rmv_'+fcnt+'" onclick="return removeit('+fcnt+')" class="close-classic"></a></div><input type="hidden" id="name_'+fcnt+'" value="'+data+'">'; $('#prv').append(img); if(fname!=='') { fname = fname+','+data; }else { fname = data; } $('#filename').val(fname); imgclean.replaceWith( imgclean = imgclean.clone( true ) ); } else { imgclean.replaceWith( imgclean = imgclean.clone( true ) ); alert('SORRY SIZE AND TYPE ISSUE'); } }); return false; }//end size else { imgclean.replaceWith( imgclean = imgclean.clone( true ) );//Its for reset the value of file type alert('Sorry File size exceeding from 1 Mb'); } }//end FILETYPE else { imgclean.replaceWith( imgclean = imgclean.clone( true ) ); alert('Sorry Only you can uplaod JPEG|JPG|PNG|GIF file type '); } }//end filecount else { imgclean.replaceWith( imgclean = imgclean.clone( true ) ); alert('You Can not Upload more than 6 Photos'); } }
这里是PHP代码:
$filetype = array('jpeg','jpg','png','gif','PNG','JPEG','JPG'); foreach ($_FILES as $key ) { $name =time().$key['name']; $path='local_cdn/'.$name; $file_ext = pathinfo($name, PATHINFO_EXTENSION); if(in_array(strtolower($file_ext), $filetype)) { if($key['name']<1000000) { @move_uploaded_file($key['tmp_name'],$path); echo $name; } else { echo "FILE_SIZE_ERROR"; } } else { echo "FILE_TYPE_ERROR"; }// Its simple code.Its not with proper validation.
这里上传和预览部分done.Now,如果你想删除和删除页面和文件夹中的图像,那么代码是在这里删除。 Ajax部分:
function removeit (arg) { var id = arg; // GET FILE VALUE var fname = $('#filename').val(); var fcnt = $('#filecount').val(); // GET FILE VALUE $('#img_'+id).remove(); $('#rmv_'+id).remove(); $('#img_'+id).css('display','none'); var dname = $('#name_'+id).val(); fcnt = parseInt(fcnt)-1; $('#filecount').val(fcnt); var fname = fname.replace(dname, ""); var fname = fname.replace(",,", ""); $('#filename').val(fname); $.ajax({ url: 'delete.php', type: 'POST', data:{'name':dname}, success:function(a){ console.log(a); } }); }
这里是PHP部分(delete.php):
$path='local_cdn/'.$_POST['name']; if(@unlink($path)) { echo "Success"; } else { echo "Failed"; }
您可以使用jquery.form.js插件通过ajax将图像上传到服务器。
http://malsup.com/jquery/form/
这里是示例jQuery ajax图片上传脚本
(function() { $('form').ajaxForm({ beforeSubmit: function() { //do validation here }, beforeSend:function(){ $('#loader').show(); $('#image_upload').hide(); }, success: function(msg) { ///on success do some here } }); })();
如果您有任何疑问,请参考以下ajax图片上传教程
http://www.smarttutorials.net/ajax-image-upload-using-jquery-php-mysql/
这里是使用HTML5和jQuery的简单方法:
1)包含两个JS文件
<script src="jslibs/jquery.js" type="text/javascript"></script> <script src="jslibs/ajaxupload-min.js" type="text/javascript"></script>
2)包括CSS有很酷的button
<link rel="stylesheet" href="css/baseTheme/style.css" type="text/css" media="all" />
3)创buildDIV或SPAN
<div class="demo" > </div>
4)将这些代码写入你的HTML页面
$('.demo').ajaxupload({ url:'upload.php' });
5)创build你的upload.php文件,让PHP代码上传数据。
你可以从这里下载所需的JS文件这里是例子
它太酷了,太快也很容易! 🙂