HTML代码
<!-- date: 2018-04-27 13:46:55 author: 王召波 descride: 多张图片上传 --> <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>Ajax+PHP实现异步上传多张图片</title> <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"> <script src="http://apps.bdimg.com/libs/jquery/2.1.4/jquery.js"></script> <style type="text/css"> #feedback{ min-height: 200px; text-align: center; border: 1px solid silver; border-radius: 3px; } #feedback img{ margin:3px 10px; border: 1px solid silver; border-radius:3px; padding: 6px; width: 35%; height: 85%; } #feedback p{ font-family: "微软雅黑"; line-height: 120px; color: #ccc; } .file { position: relative; display: inline-block; border: 1px solid #1ab294; border-radius: 4px; padding: 8px 16px; overflow: hidden; color: #fff; text-decoration: none; text-indent: 0; line-height: 20px; color: #1ab294; } .file input { position: absolute; font-size: 100px; right: 0; top: 0; opacity: 0; } .box{ margin-top: 10px; text-align: center; } .box a{ margin-left: 10px; } </style> </head> <body> <!-- 响应返回数据容器 --> <div id="feedback"> </div> <div class="box"> <a href="javascript:;" class="file">选择图片 <input type="file" multiple="multiple" id="inputfile" name="" class="photo"> </a> <a href="javascript:;" class="file close">重新选择 <input type="buttom" class="photo"> </a> </div> <script type="text/javascript"> $(document).ready(function(){ //响应文件添加成功事件 var feedback = $("#feedback"); $("#inputfile").change(function(){ if (this.files.length>2) { alert("最多只能选择两张图片"); return false; } //创建FormData对象 var data = new FormData(); //为FormData对象添加数据 $.each($('#inputfile')[0].files, function(i, file) { data.append('ruoshui'+i, file); }); //追加其他数据 data.append('id',1); //发送数据 $.ajax({ url:'./upload.php', type:'post', data:data, dataType:'json', cache: false, contentType: false, processData: false, // contentType: false 和processData: false,这两个参数是为了设置ajax对file文件对象进行序列化 success:function(data){ var str = ''; $.each(data,function(i,n){ str +='<img src="'+n+'">'; }); $("#feedback").append(str); }, error:function(){ alert('上传出错'); } }); }); $(".close").on("click",function(){ $("#feedback").empty(); }); }); </script> </body> </html>
PHP代码
<?php /** * date: 2018-04-27 13:46:55 * author: 王召波 * descride: 多张图片上传 */ header('content-type:text/html charset:utf-8'); $baseUrl = "./"; $picArr = ""; $index = 0; foreach($_FILES as $file){ $picName = 'ruoshui' . $index;//对应index.html FomData中的文件命名 $fileName = $_FILES[$picName]['name']; //文件不存在才上传 if(!file_exists($baseUrl.$fileName)) { $isMoved = false; //默认上传失败 $MAXIMUM_FILESIZE = 1 * 1024 * 1024;//文件大小限制1M = 1 * 1024 * 1024 B; $picType = "/^.(jpg|jpeg|gif|png){1}$/i"; if ($_FILES[$picName]['size'] <= $MAXIMUM_FILESIZE && preg_match($picType, strrchr($fileName, '.'))) { $isMoved = @move_uploaded_file ( $_FILES[$picName]['tmp_name'], $baseUrl.$fileName);//上传文件 } } $picArr[] = $baseUrl.$fileName; $index++; } echo json_encode($picArr);
效果图