html批量上传php,HTML5实现拖拽批量上传文件的代码
时间: 2023-12-29 12:06:23 浏览: 118
HTML5 拖拽批量上传文件的示例代码
HTML5实现拖拽批量上传文件的代码如下:
```html
<!DOCTYPE html>
<html>
<head>
<title>Drag and Drop File Upload</title>
<style>
#drop_area {
width: 200px;
height: 200px;
border: 2px dashed gray;
text-align: center;
font-size: 20px;
margin: 20px auto;
padding: 10px;
}
</style>
</head>
<body>
<div id="drop_area">
Drag and Drop Files Here
</div>
<script>
var dropArea = document.getElementById('drop_area');
// Prevent default drag behaviors
['dragenter', 'dragover', 'dragleave', 'drop'].forEach(eventName => {
dropArea.addEventListener(eventName, preventDefaults, false);
document.body.addEventListener(eventName, preventDefaults, false);
});
// Highlight drop area when dragging files over it
['dragenter', 'dragover'].forEach(eventName => {
dropArea.addEventListener(eventName, highlight, false);
});
// Remove highlight when dragging files out of drop area
['dragleave', 'drop'].forEach(eventName => {
dropArea.addEventListener(eventName, unhighlight, false);
});
// Handle dropped files
dropArea.addEventListener('drop', handleDrop, false);
function preventDefaults(e) {
e.preventDefault();
e.stopPropagation();
}
function highlight() {
dropArea.classList.add('highlight');
}
function unhighlight() {
dropArea.classList.remove('highlight');
}
function handleDrop(e) {
var dt = e.dataTransfer;
var files = dt.files;
handleFiles(files);
}
function handleFiles(files) {
files = [...files];
files.forEach(uploadFile);
}
function uploadFile(file) {
var url = 'upload.php';
var formData = new FormData();
formData.append('file', file);
fetch(url, {
method: 'POST',
body: formData
})
.then(response => {
console.log(response.text());
})
.catch(error => {
console.error(error);
});
}
</script>
</body>
</html>
```
其中,`upload.php` 是接收文件并处理的 PHP 文件。下面是一个简单的上传 PHP 文件的示例:
```php
<?php
if ($_FILES['file']['error'] === UPLOAD_ERR_OK) {
$uploadPath = './uploads/' . basename($_FILES['file']['name']);
move_uploaded_file($_FILES['file']['tmp_name'], $uploadPath);
echo 'File uploaded successfully!';
} else {
echo 'Error uploading file.';
}
?>
```
上述代码将上传的文件保存到 `uploads` 文件夹中,并返回上传成功或失败的消息。
阅读全文