PHP大文件分块上传是一种处理大文件上传的技术,它将大文件分割成多个小块,然后逐个上传这些小块,最后在服务器端将这些小块合并成一个完整的文件。这种方法可以有效避免因单个文件过大导致的内存溢出问题,提高上传的成功率和用户体验。
以下是一个简单的PHP大文件分块上传的示例代码:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>File Upload</title>
</head>
<body>
<input type="file" id="fileInput">
<button id="uploadButton">Upload</button>
<script>
document.getElementById('uploadButton').addEventListener('click', function() {
const file = document.getElementById('fileInput').files[0];
const chunkSize = 1024 * 1024; // 1MB
let offset = 0;
function uploadChunk() {
const chunk = file.slice(offset, offset + chunkSize);
const formData = new FormData();
formData.append('file', chunk, file.name);
formData.append('offset', offset);
formData.append('totalSize', file.size);
fetch('/upload.php', {
method: 'POST',
body: formData
}).then(response => response.json())
.then(data => {
if (data.success) {
offset += chunkSize;
if (offset < file.size) {
uploadChunk();
} else {
console.log('Upload complete');
}
} else {
console.error('Upload failed');
}
});
}
uploadChunk();
});
</script>
</body>
</html>
<?php
$targetDir = 'uploads/';
$fileName = $_FILES['file']['name'];
$targetFile = $targetDir . basename($fileName);
if (!file_exists($targetDir)) {
mkdir($targetDir, 0777, true);
}
$offset = intval($_POST['offset']);
$totalSize = intval($_POST['totalSize']);
$fileHandle = fopen($targetFile, 'ab');
fseek($fileHandle, $offset);
fwrite($fileHandle, file_get_contents($_FILES['file']['tmp_name']));
fclose($fileHandle);
if ($offset + filesize($_FILES['file']['tmp_name']) >= $totalSize) {
echo json_encode(['success' => true]);
} else {
echo json_encode(['success' => true]);
}
?>
upload_max_filesize
和post_max_size
设置,确保它们足够大以支持大文件上传。通过以上方法,可以有效实现PHP大文件分块上传,并解决相关问题。
领取专属 10元无门槛券
手把手带您无忧上云