发送ajax请求实现上传图片显示在网页上

时间:2023-03-09 16:19:05
发送ajax请求实现上传图片显示在网页上
 <?php
// 1,通过超全局变量来获取files[上传的图片名称]
$file = $_FILES["files"]
// 2,在通过strrchr来获取图片的格式
$ext = strrchr($file['name'],'.');
// 3,通过uniqid函数随机获取文件名避免名称重复覆盖
$filename = uniqid().$exe;
// 4,可以把获取的图片的名称存在session里面,以免后面用到,这步可写可不写;
session_start();
$_SESSION['url'] = $str;19:36:16
// 5,通过move_uploaded_file函数把上传获取的图片存在一个文件夹内
$bool = move_uploaded_file($file['tmp_name'],'../../static/uploads/'.$filename);
// 6,把处理好的图片路径返回给前端
if ($bool) {
echo "../static/uploads/" . $fileName;
} else {
echo "上传失败";
};
?> <!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>
<script src="../static/assets/vendors/jquery/jquery.min.js"></script>
<script>
$(function () {
$("#uploadImg").on("change", function () {
// console.log(this.files);
var file = this.files[0];
var data = new FormData();
data.append('file', file);
// console.log(data);
$.ajax({
type: "post",
url: "./api/_addPosts.php",
data: data,
dataType: "json",
success: function (res) {
console.log(res)
}
});
});
})
</script>
</head> <body>
<input type="file" name="" id="uploadImg">
</body> </html>