首先简单了解一下 FormData,点击链接:https://developer.mozilla.org/zh-CN/docs/Web/API/FormData/Using_FormData_Objects
IE浏览器版本最好为:IE10+,因为 FormData 兼容性问题
然后查看示例,代码如下↓
html 代码:
- <!DOCTYPE html>
- <html lang="zh-cn">
- <head>
- <meta charset="UTF-8">
- <title>Title</title>
- <script type="text/javascript" src="https://www.shangyouw.cnjquery-1.8.3.min.js"></script>
- <style type="text/css">
- #showimg{margin-top: 20px;height: 150px;}
- #showimg div{width: 100px;height: 100px;line-height:100px;margin-right: 20px;float: left;text-align: center;}
- #showimg img{vertical-align: middle;max-width: 100max-height: 100}
- </style>
- <script type="text/javascript">
- jQuery(function () {
- jQuery('#butSubmit').click(function () {
- var file = jQuery('#fileId')[0].files;
- var formDataInfo = new FormData(jQuery('#FormDataUpload')[0]);
- formDataInfo.append('file',file);//表单数据
- formDataInfo.append('ajajxfile', 1);//额外加数据
- /*------分割线------*/
- // var formDataInfo = new FormData();
- // formDataInfo.append('pic', jQuery("#picId")[0].files[0]);
- // formDataInfo.append('ajajxfile', 1);//额外加数据
- //jQuery.each(jQuery("#fileId")[0].files,function (k,val) {
- // formDataInfo.append('fileimg[]', val);
- // });
- // alert(formData);
- jQuery.ajax({
- type:'post',
- url:'upload.php',
- dataType:'json',
- cache:false,
- processData:false,//必须
- contentType:false,//必须
- data:formDataInfo,
- success:function (data) {
- // alert(data);
- var html = '';
- for (var i=0;i<data.length;i++){
- html +='<div><img src="https://www.shangyouw.cn'+data[i]+'"></div>';
- }
- jQuery('#showimg').html(html);
- },
- error:function () {
- alert('Error');
- }
- });
- });
- });
- </script>
- </head>
- <body>
- <br>
- <form id="FormDataUpload" action="upload.php" method="post" enctype="multipart/form-data">
- <input name="img[]" type="file" id="fileId" multiple>
- <!--<input name="picId" type="file" id="picId">-->
- <input type="button" value="提交" id="butSubmit">
- <!-- <input type="submit" name="dosubmit" value="提交Form">-->
- </form>
- <div id="showimg"></div>
- </body>
- </html>
后台程序 PHP代码:
- <?php
- date_default_timezone_set('PRC');
- if (!empty($_POST)){
- if ($_FILES['img']['name'][0]){
- $path = 'upload/';
- if (!is_dir($path)){
- mkdir(iconv("UTF-8", "GBK", $path),0777,true);
- }
- $datafile = $_FILES['img'];
- $filearr = array();
- foreach ($datafile['name'] as $key=>$value){
- $type = pathinfo($value);
- $filename = $path.time().mt_rand(0,999999999).'.'.$type['extension'];
- if (move_uploaded_file($datafile['tmp_name'][$key],$filename)){
- $filearr[] = $filename;
- }
- }
- print_r(json_encode($filearr));die;
- }
- }
一个简单的ajax上传文件,欢迎广大朋友们一起来学习!