这篇文章将为大家详细讲解有关JavaScript+PHP实现视频文件分片上传的示例代码,小编觉得挺实用的,因此分享给大家做个参考,希望大家阅读完这篇文章后可以有所收获。
JavaScript
// 分片大小(字节)
const CHUNK_SIZE = 1024 * 1024;
const file = document.getElementById("video-file");
const progressBar = document.getElementById("progress-bar");
const percentage = document.getElementById("percentage");
// 创建FormData用于存储分片数据
const formData = new FormData();
// 将整个视频文件添加到formData中
formData.append("video", file);
// 分片上传函数
async function uploadChunks(formData, chunkIndex = 0) {
// 获取当前分片
const chunk = formData.get("video").slice(chunkIndex * CHUNK_SIZE, (chunkIndex + 1) * CHUNK_SIZE);
// 创建新的FormData用于存储当前分片
const chunkFormData = new FormData();
chunkFormData.append("chunk", chunk);
chunkFormData.append("chunkIndex", chunkIndex);
// 发送当前分片
const response = await fetch("/upload", {
method: "POST",
body: chunkFormData,
});
// 处理响应
if (response.ok) {
// 成功上传分片
const data = await response.json();
updateProgress(data.progress);
// 如果还有分片则继续上传
if (chunkIndex * CHUNK_SIZE < file.size) {
await uploadChunks(formData, chunkIndex + 1);
}
} else {
// 上传分片失败
console.error("Error uploading chunk", response);
}
}
// 更新进度条
function updateProgress(progress) {
progressBar.value = progress;
percentage.textContent = `${progress}%`;
}
// 事件监听器
file.addEventListener("change", async () => {
updateProgress(0);
await uploadChunks(formData);
});
PHP
<?php
// 获取分片数据
$chunk = $_FILES["chunk"]["tmp_name"];
$chunkIndex = $_POST["chunkIndex"];
// 拼接文件路径
$filePath = "uploads/" . basename($_FILES["video"]["name"]);
$tempFilePath = "uploads/temp_" . basename($_FILES["video"]["name"]);
// 如果文件已存在,则删除
if (file_exists($filePath)) {
unlink($filePath);
}
// 如果临时文件已存在,则删除
if (file_exists($tempFilePath)) {
unlink($tempFilePath);
}
// 移动分片到临时文件
move_uploaded_file($chunk, $tempFilePath);
// 如果是第一个分片,则创建新文件
if ($chunkIndex === 0) {
copy($tempFilePath, $filePath);
} else {
// 将分片追加到文件中
file_put_contents($filePath, file_get_contents($tempFilePath), FILE_APPEND);
}
// 删除临时文件
unlink($tempFilePath);
// 返回进度
echo json_encode(["progress" => ($chunkIndex + 1) / ceil($_FILES["video"]["size"] / CHUNK_SIZE) * 100]);
以上就是JavaScript+PHP实现视频文件分片上传的示例代码的详细内容,更多请关注编程学习网其它相关文章!