視頻分片上傳
# 基本原理
# 簡單說就是將大文件分片上傳,完成後再將全部分片進行合併。
/**
* 資源上傳控制器
* ThinkPHP5
*/
class Upload extends Common
{
protected $chunk; // 當前上傳文件的分片數
protected $chunks; // 總分片數
protected $savepath; // 保存地址
protected $filename; // 文件名
protected $filesize; // 文件大小
/**
* 構造函數
*/
public function __construct()
{
parent::__construct();
}
/**
* 視頻分片上傳
*/
public function videoChunk()
{
// 這裏須要注意的就是設置分配的最大內存不得小於容許的最大上傳文件
set_time_limit(0);
ini_set('memory_limit', '1024M');
// 獲取文件相關信息,前端須要提交相關的文件信息
$this->chunk = input('chunk');
$this->chunks = input('chunks');
$this->savepath = '/data/video/' . date('Ymd');
$this->filename = input('name');
$this->filesize = input('filesize');
// 驗證文件大小
if ($this->filesize > (1 * 1024 * 1204 * 1024)) {
response(401, '請不要上傳超過 1G 的視頻!');
}
// 接受上傳分片
$tmpname = $this->filename . '.tmp' . $this->chunk;
$video = request()->file('video');
// 判斷是否有上傳文件,存在則執行上傳
if ($video) {
$info = $video->move($this->savepath, $tmpname);
// 判斷是否爲最後一塊,如果則合併
if ($this->chunk == ($this->chunks - 1)) {
$blob = '';
for($i=0; $i< $this->chunks; $i++){
$blob .= file_get_contents($this->savepath. '/' . $this->filename . '.tmp' . $i);
}
file_put_contents($this->savepath . '/' . $this->filename, $blob);
// 刪除文件分片
for ($i=0; $i< $this->chunks; $i++) {
@unlink($this->savepath . '/' . $this->filename . '.tmp' . $i);
}
response(200, '上傳成功!', ['path' => $this->savepath . '/' . $this->filename]);
}
}
}
}