分片上傳視頻畜疾,網(wǎng)上部分博客總結(jié)的使用方法模糊不清楚赴邻,自己總結(jié)的小demo,親測(cè)可用啡捶!粘貼代碼即可使用姥敛!不懂的可以留言!大家一起討論瞎暑!
index.html部分
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<style>
#progress{
width: 300px;
height: 20px;
background-color:#f7f7f7;
box-shadow:inset 0 1px 2px rgba(0,0,0,0.1);
border-radius:4px;
background-image:linear-gradient(to bottom,#f5f5f5,#f9f9f9);
}
.finish{
background-color: #149bdf;
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;
height: 100%;
}
form{
margin-top: 50px;
}
</style>
<script src="http://libs.baidu.com/jquery/2.0.0/jquery.min.js"></script>
</head>
<body>
<div id="progress">
<div id="finish_video" class="finish" style="width: 0%;" progress="0"></div>
<input type="hidden" name="VideoName" id="VideoName">
</div>
<div class="btn-group">
<input id="video_file" type="file" class="file-input" style="visibility: hidden">
<span class="btn btn-info btn-upload" style="float:left;" onclick="$(this).prev('input').trigger('click'); ">上傳視頻</span>
</div>
<script>
//分片上傳
//上傳視頻
var fileNameTime = Date.parse(new Date())/1000;
var video_file = document.getElementById("video_file");
var jdt_s = document.getElementById('finish_video');
var ipt_s = $('#VideoName');
var video_upload = new Upload(jdt_s,ipt_s);
video_file.onchange = function(){
fileNameTime = fileNameTime+1;
video_upload.addFileAndSend(this);
};
function Upload(jdt,ipt){
const LENGTH = 1024 * 1024;
var start = 0;
var end = start + LENGTH;
var blob;
var blob_num = 1;
var is_stop = 0;
//對(duì)外方法彤敛,傳入文件對(duì)象
this.addFileAndSend = function(that){
var file = that.files[0];
blob = cutFile(file);
sendFile(blob,file);
blob_num += 1;
};
//切割文件
function cutFile(file){
var file_blob = file.slice(start,end);
start = end;
end = start + LENGTH;
return file_blob;
}
//發(fā)送文件
function sendFile(blob,file){
var xhr = new XMLHttpRequest();
var form_data = new FormData();
var total_blob_num = Math.ceil(file.size / LENGTH);
form_data.append('file',blob);
form_data.append('blob_num',blob_num);
form_data.append('total_blob_num',total_blob_num);
form_data.append('file_name',fileNameTime+file.name.substr(file.name.lastIndexOf(".")));
//xhr.open('POST','http://lh/sp/index.php',false); //上傳文件的路徑
xhr.open('POST','http://lh/sp/index.php',false);
xhr.onreadystatechange = function () {
var progress;
var progressObj = jdt;
if(total_blob_num == 1){
progress = '100%';
}else{
progress = Math.min(100,(blob_num/total_blob_num)* 100 ) +'%';
}
progressObj.style.width = progress;
progressObj.innerHTML=progress;
var t = setTimeout(function(){
if(start < file.size && is_stop === 0){
blob = cutFile(file);
sendFile(blob,file);
blob_num += 1;
}else{
var responsePath = xhr.responseText;
var firstPath = responsePath.indexOf("{");
var lastPath = responsePath.indexOf("}");
var pathReturn = responsePath.substr(firstPath,lastPath-firstPath+1);
var pathReturnObj = eval('(' + pathReturn + ')');
ipt.val(pathReturnObj.file_path);
alert('上傳成功');
xhr = undefined;
form_data = undefined;
}
},1000);
};
xhr.send(form_data);
}
}
</script>
</body>
</html>
index.php部分
<?php
class UploadService
{
private $filepath;
private $tmpPath; //PHP文件臨時(shí)目錄
private $blobNum; //第幾個(gè)文件塊
private $totalBlobNum; //文件塊總數(shù)
private $fileName; //文件名
private $savePath; //保存路徑
private $basePath;
public function __construct($type, $tmpPath,$blobNum,$totalBlobNum,$fileName){
$this->tmpPath = $tmpPath;
$this->blobNum = $blobNum;
$this->totalBlobNum = $totalBlobNum;
$this->fileName = $fileName;
$this->savePath = date('Ymd',mb_substr($fileName,0,10));
$this->DataPath = date('Ymd',time());
$this->filepath = __DIR__.'/public/uploads/'.$type .'/'.$this->DataPath.'/'; //提前建立 __DIR__ 目錄 因?yàn)闆](méi)有創(chuàng)建權(quán)限
$this->basePath = __DIR__.'/public/uploads/'.$type;
}
//判斷是否是最后一塊,如果是則進(jìn)行文件合成并且刪除文件塊
private function fileMerge(){
if($this->blobNum == $this->totalBlobNum){
$blob = '';
for($i=1; $i<= $this->totalBlobNum; $i++){
$blob .= file_get_contents($this->filepath.'/'. $this->fileName.'__'.$i);
}
file_put_contents($this->filepath.'/'. $this->fileName,$blob);
$this->deleteFileBlob();
}
}
//刪除文件塊
private function deleteFileBlob(){
for($i=1; $i<= $this->totalBlobNum; $i++){
@unlink($this->filepath.'/'. $this->fileName.'__'.$i);
}
}
//移動(dòng)文件
private function moveFile(){
$this->touchDir();
$filename = $this->filepath.'/'. $this->fileName.'__'.$this->blobNum;
move_uploaded_file($this->tmpPath,$filename);
}
//API返回?cái)?shù)據(jù)
public function apiReturn(){
if(!file_exists($this->basePath)){
mkdir($this->basePath);
}
$this->moveFile();
$this->fileMerge();
if($this->blobNum == $this->totalBlobNum){
if(file_exists($this->filepath.'/'. $this->fileName)){
$data['code'] = 2;
$data['msg'] = 'success';
//$_SERVER['DOCUMENT_URI']=>$_SERVER['REQUEST_URI']
//$data['file_path'] = 'http://'.$_SERVER['HTTP_HOST'].dirname($_SERVER['REQUEST_URI']).str_replace('.','',$this->filepath).'/'. $this->fileName;
$data['file_path'] = '/uploads/video/'.$this->DataPath.'/'.$this->fileName;
}
}else{
if(file_exists($this->filepath.'/'. $this->fileName.'__'.$this->blobNum)){
$data['code'] = 1;
$data['msg'] = 'waiting for all';
$data['file_path'] = '';
}
}
header('Content-type: application/json');
echo json_encode($data);
}
//建立上傳文件夾
private function touchDir(){
if(!file_exists($this->filepath)){
mkdir($this->filepath);
}
}
}
function cut_upload()
{
ini_set('memory_limit', '200M');
//ini_set('memory_limit', '-1');//目前視頻上傳受 file_put_content()函數(shù)占用內(nèi)存影響
//實(shí)例化并獲取系統(tǒng)變量傳參
$upload = new UploadService('video',$_FILES['file']['tmp_name'],$_POST['blob_num'],$_POST['total_blob_num'],$_POST['file_name']);
//調(diào)用方法了赌,返回結(jié)果
$upload->apiReturn();
}
cut_upload();
目錄結(jié)構(gòu)