ajax 上传视频文件
<!DOCTYPE html> <html> <head> <title>Image Upload Form</title> <script src="//code.jquery.com/jquery-1.9.1.js"></script> <script type="text/javascript"> function submitForm() { console.log("submit event"); var fd = new FormData(document.getElementById("fileinfo")); fd.append("label", "WEBUPLOAD"); $.ajax({ url: "upload_file.php", type: "POST", data: fd, enctype: 'multipart/form-data', processData: false, // tell jQuery not to process the data contentType: false // tell jQuery not to set contentType }).done(function( data ) { console.log("PHP Output:"); console.log( data ); }); return false; } </script> </head> <body> <form method="post" id="fileinfo" name="fileinfo" onsubmit="return submitForm();"> <label>Select a file:</label><br> <input class="weui-uploader__input" accept="video/*" type="file" name="file" id="file"> <input type="submit" value="Upload" /> </form> <div id="output"></div> </body> </html>
upload_file.php
<?php $maxSize=10485760;//10M $allowedExts = array("mp4");//允许上传的格式 $extension = pathinfo($_FILES['file']['name'], PATHINFO_EXTENSION);//获取当前上传文件扩展名 $res = array('status' => 0,'message' => '','data'=>'');//随机生成移动后的文件名 //随机数据 function randName() { $str = 'abcdefghijkmnpqrstwxyz23456789'; return substr(str_shuffle($str),0,6); } //根据月日分计算并创建目录 function mk_dir(){ $dir = "upload"; if(is_dir('./' .$dir)){ return $dir; }else{ mkdir('./'.$dir,0777,true); return $dir; } } if (($_FILES["file"]["type"] == "video/mp4") && ($_FILES["file"]["size"] < $maxSize) && in_array($extension, $allowedExts)){ if ($_FILES["file"]["error"] > 0){ // echo "Return Code: " . $_FILES["file"]["error"] . "<br />"; $res['message'] = '上传视频失败!'; $res['data'] = $_FILES["file"]["error"]; }else{ $fileSize = ceil($_FILES["file"]["size"] / 1024 / 1024); $fileName = mk_dir().'/v'.date('mdhms', time()).'.'.$extension; move_uploaded_file($_FILES["file"]["tmp_name"],$fileName); $res['status'] = 1; $res['message'] = '上传视频成功!('.$fileSize.')M'; $res['data'] = $fileName; } }else{ $res['message'] = "文件上传错误,请上传不大于10M的mp4文件!"; } echo json_encode($res); ?>