<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2023/4/17
 * Time: 11:29
 */

namespace app\common\service;


use app\common\behavior\AdminLogBehavior;
use think\Controller;
use think\Db;

class UploadService extends Controller
{
    /**
     * 通用的上传
     * @param $rootpath string 指定上传路径
     * @return \think\response\Json
     */
    public function upload2path($rootpath)
    {
        if ($this->request->file('file')) {
            $file = $this->request->file('file');
        } else {
            $res['code'] = 1;
            $res['msg'] = '没有上传文件';
            return json($res);
        }
        $fileInfo = $file->getInfo();
        //获取上传文件名
        $saveFileName = $fileInfo['name'];
        //文件校验
        $web_config = Db::name('webconfig')->where('id', 1)->find();
        $info = $file->validate(['size' => $web_config['file_size'] * 1024, 'ext' => $web_config['file_type']])->rule('date')->move($rootpath, $saveFileName, false);
        if ($info) {
            (new AdminLogBehavior())->updateLastLog('上传文件：' . $rootpath . $info->getSaveName());
            $this->success('上传完成', 'index');
        } else {
            $this->error('上传失败：' . $file->getError());
        }
    }
}