tp5.1实现文件上传下载

我的大体需求就是管理员发布一个文件,然后所有文件在客户端进行渲染,界面以超链接形式。如下(客户端前端界面)
在这里插入图片描述
首先说一下思想,管理员通过一个编辑框选择上传附件,把管理员上传的附件放在服务器的一个文件夹中,同时把文件文件名(因为上传的命名规则是md5,没有规则,这里也可以直接把文件的路径放进去,看自己喜欢)放在数据库中。然后客户端的前端通过js进行动态显示所有文件名,当点击相应超链接时实现下载。

上传文件方法(tp的controller类方法),$file_title是我自己项目需要的,你可以根据自己需求改,path是你存放文件的路径

在这里插入图片描述

 public function publish_file(){
     $request=new Request();
     $file=$request->file('file');
     $mysqlId=date('YmdHis');
     //时间
     $time=date('Y-m-d  H-i-s');
     $info = $file->rule('uniqid')->move('../public/a_to_u_file/');
     $file_name = $info->getSaveName();
     $file_title=$_POST['file_title'];
     $file_obj=new File();
     if($info&&!empty($file_title)){
         $file_obj->publish_file('a-u',$file_name,$file_title,$time);
         $this->success('上传成功!','admin_home');
     }else{
         // 上传失败获取错误信息

         $this->success('上传失败,标题和文件不能为空!','admin_home');
     }
 }

数据库表的结构

在这里插入图片描述
上传后在客户端渲染动态添加超链接
在这里插入图片描述

    //获取数据库通知标题,时间等,并进行分页
    function file_list(){
        $.ajax({
            type : "GET",
            dataType:"json",
            url : "file_list",
            // 成功时调用方法,后端返回json数据
            //评论后期加上去
            success : function(response) {
              document.getElementById('file_list_div').style.display='';
                $('#file_list_total').html( '信息总数:'+response.file_count);
                for (var i = response.file_count-1; i>=0;i--){
                    $('#file_list_div .list-group').append('<li class="list-group-item">'+
                        '<a href="/gradulation_project/tp5.1/public/a_to_u_file/'+response.file_list[i].file_name+'" download="'+response.file_list[i].file_title+'"  id="'+response.file_list[i].file_id+'" file_name="'+response.file_list[i].file_name+'" onclick="downloadId(this)">'+response.file_list[i].file_title+'</a>' +
                        '<span class="badge pull-right" >发布时间:'+response.file_list[i].time+'</span></li>');
                };
            },
        });
    }

获取controller类数据库数据

    public function file_list(){
        $file=new File();
        $file_list=$file->file_list();
        return $file_list;
    }

这是model的File类的方法

 public  function get_file_name($dowanloadId){
        $file_name=Db::table('file')->field('file_name')->where('file_id',$dowanloadId)->where('type','=','a-u')->select();

        $file_name=[
            'file_name'=>$file_name,
        ];
        return $file_name;
    }

动态渲染时把href(也就是服务器文件的path)填上去,download=“filename”下载时的文件名字,功能事先,很简单。


版权声明:本文为weixin_44423938原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。