<?php
namespace app\admin\controller;

use app\admin\model\ReceiptModel;

class Upload extends Base
{
    //路径
    private $images_dir = '';
    private $files_dir = '';

    //类型
    private $type = 0;  //还可以是1 image 2 file
    //file表单对象
    private $file = '';

    public function __construct($file,$type = 1)
    {
        //登录验证
        $this->images_dir = config('admin.images_dir');
        $this->files_dir = config('admin.files_dir');
        $this->file = $file;
        $this->type = $type;

        Parent::__construct();
    }

    public function upload()
    {
        if($this->type == 1){
            $info = $this->file->validate(['ext'=>'jpg,png,gif'])
                ->move($this->images_dir);
        } else {
            $info = $this->file->validate(['ext'=>'jpg,png,gif,doc,docx,xls,xlsx,zip,rar,pdf'])
                ->move($this->files_dir);
        }

         if($info){
            $receipt = new ReceiptModel;
            $receipt->origin_name = $info->getFilename();
            if($this->type == 1)
                $receipt->src = $this->images_dir.DIRECTORY_SEPARATOR.$info->getSaveName();
            else
                $receipt->src =str_replace("\\","/",$this->files_dir.DIRECTORY_SEPARATOR.$info->getSaveName());

            $receipt->type = $this->type;
            $receipt->suffix = $info->getExtension();
            $receipt->size =$info->getSize();
            if($receipt->save()){
                return ['id'=>$receipt->id,'src'=>ltrim($receipt->src,'.')];
            } else {
                return ['faild'];
            }
        } else {
            // 上传失败获取错误信息
            return  $this->file->getError();
        }
    }
}