php – 你能用Ajax上传图片吗?
发布时间:2020-12-13 16:04:32 所属栏目:PHP教程 来源:网络整理
导读:参见英文答案 Uploading both data and files in one form using Ajax?????????????????????????????????????7个 我想使用$.ajax上传图片,但是我收到以下PHP错误: undefined index:files 这是我的HTML和JS: form id="image_form" enctype="multipart/form-
参见英文答案 >
Uploading both data and files in one form using Ajax?????????????????????????????????????7个
我想使用$.ajax上传图片,但是我收到以下PHP错误:
这是我的HTML和JS: <form id="image_form" enctype="multipart/form-data"> <input type="file" name="files[]" id="files[]" multiple > <input type="submit" name="submit" is="submit" /> </form> <div id="result"></div> <script src="js/jquery_library.js"></script> <script> $(document).ready(function() { $('#image_form').submit(function(e) { e.preventDefault(); $.ajax({ method: "POST",url: "upload.php",data: $(this).serialize(),success: function(status) { $('#result').append(status); } }); }); }); </script> 这是我的PHP: <?php include 'connect.php'; $allowed = array('jpg','png','jpeg','gif','bmp'); $myFile = $_FILES['files']; $fileCount = count($myFile["name"]); for ($i = 0; $i < $fileCount; $i++) { $name = $myFile["name"][$i]; $type = $myFile['type'][$i]; $tmp_name = $myFile['tmp_name'][$i]; $result = substr(sha1(mt_rand()),50); $explode = explode(".",$myFile["name"][$i]); $ext = end($explode); $target = "photos/".$result.".".$ext; if(in_array($ext,$allowed)) { if(move_uploaded_file($tmp_name,$target)) { mysqli_query($con,"INSERT INTO images VALUES('".$target."')"); echo "<img src='$target' />"; } } } ?> 解决方法
我已经弄明白了,这是它:
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script> <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script> <script type="text/javascript"> $(document).ready(function() { $('#image_form').submit(function(e) { e.preventDefault(); $.ajax({ url: "upload.php",type: "POST",data: new FormData(this),contentType: false,processData:false,success: function(status) { $('#result').append(status); } }); }); }); </script> //upload.php <?php include 'connect.php'; if(is_array($_FILES)) { foreach ($_FILES['files']['name'] as $name => $value) { $file_name = explode(".",$_FILES['files']['name'][$name]); $allowed_ext = array("jpg","jpeg","png","gif"); if(in_array($file_name[1],$allowed_ext)) { $new_name = substr(sha1(mt_rand()),50) . '.' . $file_name[1]; $sourcePath = $_FILES['files']['tmp_name'][$name]; $target = "photos/".$new_name; if(move_uploaded_file($sourcePath,$target)) { mysqli_query($con,"INSERT INTO images VALUES('".$target."')"); echo "<img src='$target' />"; } } } } ?> (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |