PHP 上传图片视频至阿里云OSS
·
public function upload(Request $request): Json
{
if ($request->isPost()) {
$param = $request->param();
$field = $param['file_field'] ?? 'file';
$dir = $param['file_dir'] ?? 'uploads';
// 文件类型,默认图片
$file_type = $param['file_type'] ?? 'image';
// 上传到本地,可自行修改为oss之类的
$config = config('filesystem.disks.aliyun');
$filess = $request->file();
try {
validate([$field => $config['validate'][$file_type]])->check($filess);
} catch (ValidateException $e) {
return json([
'message' => $e->getMessage()
], 500);
}
$file = $filess[$field];
$files = $_FILES[$field];
$name = $files['name'];
$format = strrchr($name, '.'); //截取文件后缀名如 (.jpg)
// 阿里云主账号AccessKey拥有所有API的访问权限,风险很高。强烈建议您创建并使用RAM账号进行API访问或日常运维,请登录RAM控制台创建RAM账号。
$accessKeyId = $config['accessId'];
$accessKeySecret = $config['accessSecret'];
// Endpoint以北京为例,其它Region请按实际情况填写。
$endpoint = $config['endpoint'];
// 设置存储空间名称。
$bucket = $config['bucket'];
$object = 'uploads/' . date('Ymd') . '/' . sha1(date('YmdHis', time()) . uniqid()) . $format;
$filePath = $files['tmp_name'];
try {
$ossClient = new OssClient($accessKeyId, $accessKeySecret, $endpoint);
$result = $ossClient->uploadFile($bucket, $object, $filePath);
if (!$result) {
return json(['status' => 1, 'message' => '上传失败']);
} else {
$url = str_replace("http://zitisheji2022.oss-cn-beijing.aliyuncs.com", "https://oss.zitisheji.com", $result['info']['url']);
$infos = getimagesize($url);
$width = $infos[0];
$hight = $infos[1];
$ratio = 330 / $width;
$imghight = round($hight * $ratio);
return json([
'code' => 200,
'initialPreview' => [$url],
'initialPreviewAsData' => true,
'showDownload' => false,
'initialPreviewConfig' => [
[
'downloadUrl' => $url,
'key' => str_replace("\\", '/', $name),
'caption' => str_replace("\\", '/', $name),
'url' => url('admin/file/del', ['file' => $url])->build(),
'size' => $file->getSize(),
'high' => $imghight,
]
]
]);
}
} catch (OssException $e) {
return json([
'message' => $e->getMessage()
], 500);
}
}
return api_error('非法访问');
}
魔乐社区(Modelers.cn) 是一个中立、公益的人工智能社区,提供人工智能工具、模型、数据的托管、展示与应用协同服务,为人工智能开发及爱好者搭建开放的学习交流平台。社区通过理事会方式运作,由全产业链共同建设、共同运营、共同享有,推动国产AI生态繁荣发展。
更多推荐


所有评论(0)