上传文件

1. 上传表单(这里以上传视频为例):

<form action="./upload_handle.php" method="post" enctype="multipart/form-data">

  视频名称:<input type="text" name="name" />

  <input type="file" name="video" accept="video/*">

  <input type="submit" value="确定添加"/>

</form>

2. 上传处理:

//函数功能:根据文件上传时间生成新文件名

//参数:原文件名

function mkFileName($fName) {

  $curTime = getdate();

  //获取文件后缀名

  $fileExt = substr(strrchr($fName,'.'), 1);

  $newFileName = $curTime['year'] . $curTime['mon'] . $curTime['mday'] . $curTime['hours'] . 

  $curTime['minutes'] . $curTime['seconds'] . '.' . $fileExt;

  return $newFileName;

}

if($_POST) {

  //判断视频文件是否上传成功

  if(empty($_FILES['video']['tmp_name'])) {

  echo "<script>alert('视频上传失败!');location.href='" . $_SERVER["HTTP_REFERER"] . "';</script>";

  exit();

  }

  //判断保存视频文件的目录是否存在,若不存在则创建之

  $upload_dir = getcwd() . "\videos\";

  if(! is_dir($upload_dir)) {

  mkdir($upload_dir);

  }

  //生成新文件名和路径

  $newFileName = mkFileName($_FILES['video']['name']);

  $location = './videos/' . $newFileName;

  //将文件移动至目标位置

  if(move_uploaded_file($_FILES['video']['tmp_name'], $location)) {

  //添加数据库记录

  //返回上一页并刷新页面

  echo "<script>alert('视频上传成功!');location.href='" . $_SERVER["HTTP_REFERER"] . "';</script>";

  } else {

  echo "<script>alert('视频上传失败!');location.href='" . $_SERVER["HTTP_REFERER"] . "';</script>";

  }

}

原文地址:https://www.cnblogs.com/wujuntian/p/4468002.html