php实现图片、PDF、DOC、TXT多种文件上传下载功能(附源码)

 DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>上传文件title>
head>
<body>
  <form action="{:U('Admin/Down/uploadfile')}" enctype="multipart/form-data" method="post" style="text-align:center;margin:30px;">
    <input type="file" name="photo"/>
    <input type="hidden" name="MAX_FILE_SIZE" value="204800" />
    <input type="hidden" name="type" value="webfile"/>
    <input type="submit" value="确定上传">
  form>
body>
html>

//上传方法

 public function uploadfile(){
    $type=$_POST['type'];
    $chat=$_POST['phpto_chat'];
    $showname=$_POST['name'];
    $upload = new \Think\Upload();// 实例化上传类
    $upload->maxSize   =     3145728 ;// 设置附件上传大小
    $upload->exts      =     array('jpg', 'gif', 'png', 'jpeg','pdf','doc','docx','txt');
    // 设置附件上传类型
    $upload->rootPath  =     './Upload/file/'; // 设置附件上传根目录
    $upload->savePath  =     ''; // 设置附件上传(子)目录
    $upload->subName  = array('date','Ymd');
    $upload->saveName = array('uniqid','');
    // $upload->saveName = '';
    // 上传文件
    $info   =   $upload->upload();
    $data['pubtime'] = NOW_TIME;
    if(!$info) {// 上传错误提示错误信息
        $this->error($upload->getError());
    }else{// 上传成功
      // die(var_dump($type));
      $data['path'] = '/Upload/file/'.$info['photo']['savepath'].$info['photo']['savename'];
      $size=$info['photo']['size'];
      if($size>1024){
        $lastsize=intval($size/1024).'KB';
      }
      if(($size/1024)>1024){
        $lastsize=intval($size/1048576).'MB';
      }
      $downdata=array(
        'title'=>$info['photo']['name'],
        'type'=>$info['photo']['ext'],
        'size'=>$lastsize,
        'src'=>$data['path'],
        'time'=>time(),
      );
      $result = $this->downModle->add($downdata); //保存数据库
      if($result>0){
          $this->success("添加成功!", U('Admin/down/index'), 1);
      }else{
          $this->error("添加失败!", U('Admin/down/index'), 1);
      }
      $this->alertOpenerClose($data['path']);

    }
  }
//下载功能
    public function downfile(){
    if(isset($_GET['id'])){
      $data=$this->downModle->where('id='.$_GET['id'])->field('src,title')->select();
      $filename=$data[0]['src'];//获取文件的相对路径
      $title=$data[0]['title'];//获取文件的名称,必须带后缀格式
    }

   Header( "Content-type:  application/octet-stream ");
   Header( "Accept-Ranges:  bytes ");
   Header( "Accept-Length: " .filesize($filename));
   header( "Content-Disposition:  attachment;  filename= $title");//如果没带格式将生成不知道什么格式的文件
   echo file_get_contents('http://www.100txy'.$filename);//用绝对路径
   readfile($filename);
    }

php实现图片、PDF、DOC、TXT多种文件上传下载功能(附源码)_第1张图片

你可能感兴趣的:(PHP学习记录,php,开发语言,后端)