ajax異步上傳文件和表單同步上傳文件 的區別


1. 用表單上傳文件(以照片為例)-同步上傳

html部分代碼:這里請求地址index.php

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
<form action="index.php" enctype="multipart/form-data" method="post">
<input type="file" name="photo">
<input type="submit" value="提交">
</form>
</body>
</html>
 
php結構代碼
<?php

// print_r($_FILES['photo']);

$file = $_FILES['photo'];
$name = strrchr($file['name'],".");
$name = time() . rand(0,9999) . $name;
$path = "./upload/$name";
move_uploaded_file($file['tmp_name'],$path);

?>
需要新建一個upload文件夾存儲文件
 
2.ajax異步上傳文件,代碼如下,待會總結區別
 
html
 
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
<form>
<input type="file" name="photo" id="p">
</form>
<script>
// 注冊change事件
p.onchange = function () {
// 實例對象
var xhr = new XMLHttpRequest();
// 請求行 必須用post 文件上傳你懂得
xhr.open('post','index.php');
// 實例對象
var formdata = new FormData();
// p是文件表單的DOM對象有個files屬性,直接獲取文件信息
var filemess = p.files[0];
// 添加到實例對象中
formdata.append('photo',filemess);
// 發送請求 親測成功 就不監聽狀態改變事件了 php代碼保持不變
xhr.send(formdata);
}
 
</script>
</body>
</html>

php 不變

<?php

// print_r($_FILES['photo']);

$file = $_FILES['photo'];
$name = strrchr($file['name'],".");
$name = time() . rand(0,9999) . $name;
$path = "./upload/$name";
move_uploaded_file($file['tmp_name'],$path);

?>
 
 
 
區別 : form 提交 里面需要寫屬性 而ajax提交不需要
form 同步上傳  ajax異步上傳
都是post,php獲取方式也一樣
然后需要的話把代碼貼上去看看,親測沒bug,純手寫,不喜勿噴!!!
 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM