下面是一个代码片段,用于form表单上传视频文件。
HTML部分:
PHP部分:
- <?php
- /**
- * Function:接收视频文件并存储
- */
- set_time_limit(0);
- $path = $_SERVER['DOCUMENT_ROOT']."/uploads/videos";
- $max_size = 20971520; //20Mb限制
- $allow_file_type = ['mov','mp4','wmv','rm','rmvb','mpg','flv','swf'];
- if(!emptyempty($_FILES['videos'])){
- if($_FILES['videos']['size'] >= $max_size){
- echo json_encode(['errcode'=>"fail",'msg'=>"上传文件不能超过20M"]);
- }
- $file_ext = pathinfo($_FILES['videos']['name']);
- if(in_array($file_ext['extension'],$allow_file_type)){
- $uploaded_file=$_FILES['videos']['tmp_name'];
- if(!file_exists($path)){
- mkdir($path,0777,true);
- }
- $file_true_name=$_FILES['videos']['name'];
- $move_dir = $path."/".time().rand(1,1000).substr($file_true_name,strrpos($file_true_name,"."));
- if(move_uploaded_file($uploaded_file,iconv("utf-8","gb2312",$move_dir))){
- $file_path = pathinfo($move_dir);
- $file_url = "/uploads/videos/".$file_path['basename'];
- echo json_encode(['errcode'=>"ok",'msg'=>"上传成功",'file_url'=>$file_url]);
- }else{
- echo json_encode(['errcode'=>"fail",'msg'=>"上传失败"]);
- }
- }else{
- echo json_encode(['errcode'=>"fail",'msg'=>"文件类型有误"]);
- }
- }else{
- echo json_encode(['errcode'=>"fail",'msg'=>"上传文件不能为空"]);
- }
- exit;
上传视频需要注意的是前端数据提交方式必须和后台保持一致,否则就会出现提交数据,后台获取不到的情况。