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,纯手写,不喜勿喷!!!