html部分
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>切片上传</title>
</head>
<!--引入CSS-->
<link rel="stylesheet" type="text/css" href="https://cdn.bootcss.com/webuploader/0.1.1/webuploader.css">
<style>
.progress {
height: 20px;
margin-bottom: 20px;
overflow: hidden;
background-color: #f5f5f5;
border-radius: 4px;
-webkit-box-shadow: inset 0 1px 2px rgba(0,0,0,0.1);
box-shadow: inset 0 1px 2px rgba(0,0,0,0.1);
}
.progress.active .progress-bar {
-webkit-animation: progress-bar-stripes 2s linear infinite;
animation: progress-bar-stripes 2s linear infinite;
}
.progress-striped .progress-bar {
background-image: linear-gradient(45deg,rgba(255,255,255,0.15) 25%,transparent 25%,transparent 50%,rgba(255,255,255,0.15) 50%,rgba(255,255,255,0.15) 75%,transparent 75%,transparent);
background-size: 40px 40px;
}
.progress-bar {
background-image: -webkit-linear-gradient(top,#428bca 0,#3071a9 100%);
background-image: linear-gradient(to bottom,#428bca 0,#3071a9 100%);
background-repeat: repeat-x;
filter: progid:DXImageTransform.Microsoft.gradient(startColorstr=’#ff428bca’,endColorstr=’#ff3071a9’,GradientType=0);
}
.progress-bar {
float: left;
height: 100%;
font-size: 12px;
line-height: 20px;
color: #fff;
text-align: center;
background-color: #428bca;
box-shadow: inset 0 -1px 0 rgba(0,0,0,0.15);
transition: width .6s ease;
}
</style>
<body>
<h1>PHP的大文件切片上传</h1>
<div id="uploader">
<div id="thelist" class="uploader-list"></div>
<div class="btns">
<table style="width: 300px;" border="1">
<tr align="right">
<td>
<div id="picker" style="float:left">选择文件</div>
</td>
<td>
<button id="ctlBtn" class="btn btn-default" style="padding:8px 15px;">开始上传</button>
</td>
</tr>
</table>
</div>
</div>
</body>
<script src="https://cdn.bootcdn.net/ajax/libs/jquery/1.10.0/jquery.min.js"></script>
<script src="https://cdn.bootcss.com/webuploader/0.1.1/webuploader.js"></script>
<script>
$(function () {
let $list = $("#thelist"); //初始化
let $btn = $("#ctlBtn"); //开始上传
let uploader = WebUploader.create({
// 选完文件后,是否自动上传。
auto: false,
// swf文件路径
swf: "https://cdn.bootcdn.net/ajax/libs/webuploader/0.1.1/Uploader.swf",
// 文件接收服务端。
server: "Upload.php",
accept: {
title: "Video Files",
// extensions: "dat,asf,rm,ram,3gp,mov,m4v,dvix,dv,qt,divx,cpk,fli,flc,mod,mp4,wmv,flv,avi,mkv,vob,mpg,rmvb,mpeg,mov,mts",
},
// 选择文件的按钮。可选。
// 内部根据当前运行是创建,可能是input元素,也可能是flash.
pick: '#picker',
// mulitple:true,//选择多个
chunked: true,//开启分片上传
chunkSize: 2 * 1024 * 1024,//分片大小,建议2M,其他可能需要设置
threads: 3,//上传并发数
method: 'POST',
});
// 当有文件添加进来的时候
uploader.on('fileQueued', function (file) {
// webuploader事件.当选择文件后,文件被加载到文件队列中,触发该事件。等效于 uploader.onFileueued = function(file){...} ,类似js的事件定义。
$list.append('<div id="' + file.id + '" class="item">' +
'<h4 class="info">' + file.name + '</h4>' +
'<p class="state">等待上传...</p>' +
'</div>');
});
// 文件上传过程中创建进度条实时显示。
uploader.on('uploadProgress', function (file, percentage) {
var $li = $('#' + file.id),
$percent = $li.find('.progress .progress-bar');
// 避免重复创建
if (!$percent.length) {
$percent = $('<div class="progress progress-striped active">' +
'<div class="progress-bar" role="progressbar" style="width: 0%">' +
'</div>' +
'</div>').appendTo($li).find('.progress-bar');
}
$li.find('p.state').text('上传中');
$percent.css('width', percentage * 100 + '%');
});
// 文件上传成功,给item添加成功class, 用样式标记上传成功。
uploader.on('uploadSuccess', function (file, response) {
$('#' + file.id).addClass('upload-state-done');
let urls = response.data;
console.log(urls);
// $("#link_key").val(urls);
});
// 文件上传失败,显示上传出错。
uploader.on('uploadError', function (file) {
$('#' + file.id).find('p.state').text('上传出错');
});
// 完成上传完了,成功或者失败,先删除进度条。
uploader.on('uploadComplete', function (file) {
// alert(file.id)
// alert(file);
$('#' + file.id).find('.progress').remove();
$('#' + file.id).find('p.state').text('已上传');
// // $('.layui-video-box').html(Help.videoHtml(url, key));
// Help.video_read();
// location.href="http://www.xiaosan.com/tp5/public/index.php/index/backstage/vioshow";
});
$btn.on('click', function () {
if ($(this).hasClass('disabled')) {
return false;
}
uploader.upload();
});
});
</script>
</html>
php部分
<?php
class Upload
{
/**
* 上传接口
* $targetDir 切片保留路径(可自行修改)
* $uploadDir 最终上传路径(可自行修改)
* $domain 域名(可自定义修改)
* $urls 返回地址(可自定义修改)
* @return mixed
*/
public function uploadVideo()
{
// Make sure file is not cached (as it happens for example on iOS devices)
header("Access-Control-Allow-origin:*");
//header("Access-Control-Allow-Credentials:true");
//header('Access-Control-Allow-Headers:x-requested-with,content-type');
header("Expires: Mon, 26 Jul 1997 05:00:00 GMT");
header("Last-Modified: ".gmdate("D, d M Y H:i:s")." GMT");
header("Cache-Control: no-store, no-cache, must-revalidate");
header("Cache-Control: post-check=0, pre-check=0", false);
header("Pragma: no-cache");
// Support CORS
// header("Access-Control-Allow-Origin: *");
// other CORS headers if any...
if ($_SERVER['REQUEST_METHOD'] == 'OPTIONS') {
exit; // finish preflight CORS requests here
}
if (!empty($_REQUEST['debug'])) {
$random = rand(0, intval($_REQUEST['debug']));
if ($random === 0) {
header("HTTP/1.0 500 Internal Server Error");
exit;
}
}
//
//var_dump($_REQUEST);
//
// header("HTTP/1.0 500 Internal Server Error");
// exit;
// 5 minutes execution time
@set_time_limit(5 * 60);
$targetDir = 'upload_temp'; //切片保留路径(可自行修改["名称+_temp"])
$uploadDir = 'upload/'.date('Ymd');//最终上传路径(可自行修改)
$cleanupTargetDir = true; // Remove old files
$maxFileAge = 5 * 3600; // Temp file age in seconds
// Create target dir
if (!file_exists($targetDir)) {
@mkdir($targetDir, 0777, true);
}
// Create target dir
if (!file_exists($uploadDir)) {
@mkdir($uploadDir, 0777, true);
}
// Get a file name
if (isset($_REQUEST["name"])) {
$fileName = $_REQUEST["name"];
} elseif (!empty($_FILES)) {
$fileName = $_FILES["file"]["name"];
} else {
$fileName = uniqid("file_");
}
$ext = strrchr($fileName, '.');
$times = md5(microtime(true));
$fileNames = $times.$ext;
$filePath = str_replace('\\', '/', $targetDir.DIRECTORY_SEPARATOR.$fileName);
// $uploadPath = $uploadDir . DIRECTORY_SEPARATOR . $fileNames;
$uploadPath = str_replace('\\', '/', $uploadDir.DIRECTORY_SEPARATOR.$fileNames);
$domain = 'http://codes.com';//配置域名可自行修改
$urls = $domain.'/'.$uploadPath;
// Chunking might be enabled
$chunk = isset($_REQUEST["chunk"]) ? intval($_REQUEST["chunk"]) : 0;
$chunks = isset($_REQUEST["chunks"]) ? intval($_REQUEST["chunks"]) : 1;
// Remove old temp files
if ($cleanupTargetDir) {
if (!is_dir($targetDir) || !$dir = opendir($targetDir)) {
// echo '123';
die('{"jsonrpc" : "2.0", "error" : {"code": 100, "message": "Failed to open temp directory."}, "id" : "id","uploadPath":$uploadPath}');
}
while (($file = readdir($dir)) !== false) {
$tmpfilePath = $targetDir.DIRECTORY_SEPARATOR.$file;
// If temp file is current file proceed to the next
if ($tmpfilePath == "{$filePath}_{$chunk}.part" || $tmpfilePath == "{$filePath}_{$chunk}.parttmp") {
continue;
}
// Remove temp file if it is older than the max age and is not the current file
if (preg_match('/\.(part|parttmp)$/', $file) && (@filemtime($tmpfilePath) < time() - $maxFileAge)) {
@unlink($tmpfilePath);
}
}
closedir($dir);
}
// Open temp file
if (!$out = @fopen("{$filePath}_{$chunk}.parttmp", "wb")) {
die('{"jsonrpc" : "2.0", "error" : {"code": 102, "message": "Failed to open output stream."}, "id" : "id"}');
}
if (!empty($_FILES)) {
if ($_FILES["file"]["error"] || !is_uploaded_file($_FILES["file"]["tmp_name"])) {
die('{"jsonrpc" : "2.0", "error" : {"code": 103, "message": "Failed to move uploaded file."}, "id" : "id"}');
}
// Read binary input stream and append it to temp file
if (!$in = @fopen($_FILES["file"]["tmp_name"], "rb")) {
die('{"jsonrpc" : "2.0", "error" : {"code": 101, "message": "Failed to open input stream."}, "id" : "id"}');
}
} else {
if (!$in = @fopen("php://input", "rb")) {
die('{"jsonrpc" : "2.0", "error" : {"code": 101, "message": "Failed to open input stream."}, "id" : "id"}');
}
}
while ($buff = fread($in, 4096)) {
fwrite($out, $buff);
}
@fclose($out);
@fclose($in);
rename("{$filePath}_{$chunk}.parttmp", "{$filePath}_{$chunk}.part");
$index = 0;
$done = true;
for ($index = 0; $index < $chunks; $index++) {
if (!file_exists("{$filePath}_{$index}.part")) {
$done = false;
break;
}
}
if ($done) {
if (!$out = @fopen($uploadPath, "wb")) {
// echo '1';
die('{"jsonrpc" : "2.0", "error" : {"code": 102, "message": "Failed to open output stream."}, "id" : "id"}');
}
if (flock($out, LOCK_EX)) {
for ($index = 0; $index < $chunks; $index++) {
if (!$in = @fopen("{$filePath}_{$index}.part", "rb")) {
break;
}
while ($buff = fread($in, 4096)) {
fwrite($out, $buff);
}
@fclose($in);
@unlink("{$filePath}_{$index}.part");
}
flock($out, LOCK_UN);
}
@fclose($out);
}
exit(json_encode(['code' => 200, 'msg' => 'ok', 'data' => $urls]));
}
}
//调用
$demo = new Upload();
$demo->uploadVideo();