<?php
namespace app\api\controller;

use app\model\Uploads;
use support\Request;

class UploadController extends base
{
    public function index(Request $request)
    {
        $file = $request->file("file");

        if (!$file->isValid()) {
            return $this->error(400, 'upload fail, code=' . $file->getUploadErrorCode());
        }
//        if (!in_array($file->getExtension(), ['jpg', 'png', 'jpeg']) ){
//            return $this->error(400, '请选择图片,文件后缀:'.$file->getFilename());
//        }

        $now = date_create();
        $savepath = sprintf("/uploads/%d/%s/%s", 1, $now->format("YmdHisu"), $file->getUploadName());
        $item = new Uploads();
        $item->admin_id = 0;
        $item->filesize = 0;
        $item->filepath = $savepath;
        $item->mime = $file->getUploadMimeType();
        $item->create_at = $now->getTimestamp();

        $file->move(public_path(). $savepath);
        $item->save();

        return $this->success(env('APP_URL') . $savepath);
    }
}