Laravel 上传文件到阿里云
2021-03-05 21:27
标签:文件 OLE || efi secret php mod moni 阿里 在laravel 安装的根目录下,执行命令 composer require aliyuncs/oss-sdk-php 下载阿里云sdk。 //上传图片 @return array|string } } if(empty($attachment)){ Laravel 上传文件到阿里云 标签:文件 OLE || efi secret php mod moni 阿里 原文地址:https://blog.51cto.com/3154408/2495793
use OSS\Core\OssException;
use OSS\OssClient;
class uploadImgCombine
{
/**
*/
public function uploadLocalToOss($sourcePath, $format = ‘jpg‘, $imgFullName = ‘‘, $folder = ‘‘, $save = false)
{
//检查图片是否是OSS地址
if (!file_exists($sourcePath))
{
return [‘msg‘ => ‘文件不存在‘, ‘code‘ => 1001];
}// 文件名称(传到OOS后要保证唯一,重名的无法上传)
$object = $imgFullName ? $imgFullName : date(‘YmdHis‘).CommonHelpers::rand(4, 0).‘.‘.$format;
//oss保存地址
$ossSaveFilePath = $folder ? $folder.‘/‘.$object : $object;
//读取配置
//$conf = json_decode(getenv(‘ALIYUN‘), true);
//$accessKeyId = $conf[‘appkey‘] ?? ‘‘;
//$accessKeySecret = $conf[‘secret‘] ?? ‘‘;
//$endpoint = $conf[‘endpoint‘] ?? ‘‘;
$accessKeyId = env(‘ALIYUN_ACCESS_KEY_ID‘);
$accessKeySecret = env(‘ALIYUN_ACCESS_KEY_SECRET‘);
$endpoint = env(‘ALIYUN_OSS_ENDPOINT‘);
// 存储空间名称
$bucket = env(‘ALIYUN_OSS_BUCKET‘) ?? ‘‘;
try
{
//上传
$ossClient = new OssClient($accessKeyId, $accessKeySecret, $endpoint);
$rel = $ossClient->uploadFile($bucket, $ossSaveFilePath, $sourcePath);
}
catch (OssException $e)
{
return [‘msg‘ => $e->getMessage(), ‘code‘ => $e->getCode()];
}
//验证是否上传成功
if (isset($rel[‘oss-request-url‘]))
{
$id = ‘‘;
//保存到数据库
/*if($save)
{
$id = CommonImageModel::saveOneData([
‘root_url‘ => $ossSaveFilePath,
‘small_url‘ => $ossSaveFilePath,
‘create_time‘ => time(),
‘origin_url‘ => ‘‘,
]);
}*/
return [
‘filePath‘ => env(‘ALIYUN_OSS_URL‘) . $ossSaveFilePath,
‘id‘ => $id
];
}
//返回
return [‘msg‘ => ‘上传失败‘, ‘code‘ => 1201];
使用这个类
return JsonResult::fail([],‘请上传文件‘);
} if($attachment->getSize() > 300*1024*1024)
{
return JsonResult::fail([],‘上传作品不能超过300M‘);
}
if(!$attachment || !$attachment->isValid())
{
return JsonResult::fail([],‘上传作品失败‘);
}
//上传
$filePath = $attachment->getRealPath(); //获取文件临时存放位置
$format = $attachment->getClientOriginalExtension();//上传文件的后缀
$result = (new uploadImgCombine())->uploadLocalToOss($filePath, $format, ‘‘, ‘work‘, true);
//返回
if(isset($result[‘msg‘]))
{
return JsonResult::fail([], $result[‘msg‘], $result[‘code‘]);
}
$attachment_path = $result[‘filePath‘];