<?php

namespace app\admin\controller;

use app\model\FileModel;
use think\facade\Filesystem;

class Upload extends AdminBaseController
{

    // 上传图片
    public function upload()
    {
        try {
            // 获取文件
            $file = $this->request->file('file');
            $param = $this->request->param();
            $rootPath = $param['path'] ?? '';
            $filename = $param['name'] ?? '';

            // 将文件存储在本地
            $name = Filesystem::disk('local')->putFile($rootPath, $file);
            $path = '/bs/image/' . $name;

            if (!empty($filename) && file_exists(app()->getRootPath() . 'public' . $path)) {
                $newName = app()->getRootPath() . 'public/bs/' . $filename;
                copy(app()->getRootPath() . 'public' . $path, $newName);
                unlink(app()->getRootPath() . 'public' . $path);
                $path = '/bs/' . $filename;
            }

            // 返回路径
            return json(['code' => '0', 'message' => '上传成功', 'data' => ['path' => $path]]);
        } catch (\Exception $exception) {
            return json(['code' => '100500', 'message' => '系统繁忙', 'data' => [$exception->getMessage()]]);
        }
    }

}