ajax图片上传
使用AJAX实现图片上传,你可以创建一个表单并使用JavaScript的FormData
对象来构建和发送POST请求。以下是一个简单的实现示例:
HTML部分:
<form id="uploadForm">
<input type="file" name="image" id="image" />
<input type="button" value="Upload" onclick="uploadImage()" />
</form>
<div id="status"></div>
JavaScript部分:
function uploadImage() {
var formData = new FormData();
var imageFile = document.getElementById('image').files[0];
formData.append('image', imageFile);
var xhr = new XMLHttpRequest();
xhr.open('POST', 'upload.php', true);
xhr.onload = function() {
if (this.status == 200) {
document.getElementById('status').innerHTML = this.responseText;
}
};
xhr.send(formData);
}
PHP部分 (upload.php
):
<?php
if ($_FILES['image']['error'] == UPLOAD_ERR_OK) {
$tmpName = $_FILES['image']['tmp_name'];
$name = $_FILES['image']['name'];
move_uploaded_file($tmpName, "uploads/$name");
echo "File uploaded successfully.";
} else {
echo "Upload failed with error: " . $_FILES['image']['error'];
}
?>
确保服务器配置允许通过POST方法上传文件,并且upload.php
文件存在于服务器上,且有适当的权限。
评论已关闭