<?php


namespace App\Http\Controllers\Api;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage;

class UploadController extends Controller
{
    public function upload(Request $request)
    {
        try {
            //获取上传的文件
            $file = $request->file('file');
            //获取上传图片的临时地址
            $tmppath = $file->getRealPath();
            //生成文件名
            $fileName = rand(1000,9999). time() .date('ymd') . '.' . $file->getClientOriginalExtension();
            //拼接上传的文件夹路径(按照日期格式1810/17/xxxx.jpg)
            $pathName = 'chengluApp/'.date('Y-m/d').'/'.$fileName;

            //上传图片到阿里云OSS
            Storage::putRemoteFile($pathName, $tmppath);
            //获取上传图片的Url链接
            $Url = Storage::url($pathName);
        }catch (\Exception $exception){
            return $this->response->errorForbidden($exception->getMessage());
        }

        // 返回状态给前端，Laravel框架会将数组转成JSON格式
        return response()->json(['src' => $Url]);
    }
}
