(前后端交互式)Ajax上传图片 + 更换背景图片
前端代码:
<!DOCTYPE html>
<html>
<head>
<title>Change Background Image</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
</head>
<body>
<form id="upload_form" enctype="multipart/form-data">
<input type="file" name="file" id="file" />
<input type="button" value="Upload" id="upload"/>
</form>
<script>
$(document).ready(function(){
$('#upload').click(function(){
var form_data = new FormData($('#upload_form')[0]);
$.ajax({
type:'POST',
url:'upload.php',
data:form_data,
contentType: false,
cache: false,
processData: false,
success:function(data){
alert(data);
$('body').css("background-image", "url('"+data+"')");
}
});
});
});
</script>
</body>
</html>
后端代码(PHP):
<?php
if(isset($_FILES['file'])){
$file = $_FILES['file'];
$fileName = $_FILES['file']['name'];
$fileTmpName = $_FILES['file']['tmp_name'];
move_uploaded_file($fileTmpName, "uploads/".$fileName);
echo "uploads/".$fileName;
}
?>
确保服务器配置正确,允许通过PHP上传文件,并且有写入权限。上面的代码实现了通过Ajax上传图片到服务器,并且在成功上传后更换了页面背景图片。
评论已关闭