首页 > 编程语言 >PHP文件上传接口

PHP文件上传接口

时间:2024-06-11 10:47:11浏览次数:45  
标签:status 文件 return 接口 file msg PHP 上传

文件上传接口

上传在项目/runtime/storage/下,返回的是相对路径.


    /**
     * 文件上传接口
     * param file: /2024-06-11_09-50-43.png
     * return
     * {
     * "status": 1,
     * "msg": "上传成功",
     *  "data": {
     *     "file_path": "/uploads/20240611/6a2282ada486c614e170dff06063527f.png"
     *  }
     * }
     */
    public function uploadAjax()
    {
        // 获取上传的文件
        $file = Request::file('file');

        // 验证规则
        $validate = Validate::rule([
            'file' => 'fileExt:jpg,jpeg,png,gif|fileSize:10485760', // 限制文件扩展名和大小
        ]);
        // 验证文件
        if (!$validate->check(['file' => $file])) {
            return json(['status' => 0, 'msg' => $validate->getError()]);
        }

        // 上传文件
        try {
            /**
             * 存储在/www/wwwroot/项目名/runtime/storage/下面指定的uploads文件夹中
             */
            $savename = Filesystem::putFile('uploads', $file);
            return json(['status' => 1, 'msg' => '上传成功', 'data' => ['file_path' => '/' . $savename]]);
        } catch (\Exception $e) {
            return json(['status' => 0, 'msg' => $e->getMessage()]);
        }
    }

标签:status,文件,return,接口,file,msg,PHP,上传
From: https://www.cnblogs.com/aeolian/p/13454067.html

相关文章