文件上传
This commit is contained in:
@@ -7,6 +7,8 @@ namespace app\controller;
|
||||
//use Webman\Http\Response;
|
||||
|
||||
use app\util\Util;
|
||||
use app\service\OssService;
|
||||
use Shopwwi\WebmanFilesystem\Facade\Storage;
|
||||
use support\Log;
|
||||
use support\Request;
|
||||
|
||||
@@ -95,4 +97,38 @@ class UploadController
|
||||
return Util::fail([],$e->getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
// 上传单文件图片
|
||||
public function uploadImage(Request $request)
|
||||
{
|
||||
try {
|
||||
$file = $request->file('files');
|
||||
|
||||
if (!$file || !$file->isValid()) {
|
||||
return Util::fail($file,'上传失败');
|
||||
}
|
||||
|
||||
$result = Storage::adapter('oss')
|
||||
->path('vehicle_album/'.date('Ymd'))
|
||||
->size(1024*1024*5)
|
||||
->extYes(['image/jpeg','image/png'])
|
||||
->extNo(['image/gif'])
|
||||
->upload($file);
|
||||
|
||||
$ossservice = new OssService();
|
||||
|
||||
$data = [
|
||||
'image_name' => $result->file_name,
|
||||
'image_url' => $ossservice->generatePrivateUrl($result->file_name)
|
||||
];
|
||||
|
||||
|
||||
return Util::success($data,'上传成功');
|
||||
}catch (\Throwable $e){
|
||||
Log::error('文件上传失败: ' . $e->getMessage());
|
||||
|
||||
return Util::fail([],'file:'.$e->getFile().'line:'.$e->getLine().'message:'.$e->getMessage());
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,55 @@
|
||||
<?php
|
||||
|
||||
namespace app\service;
|
||||
|
||||
use OSS\OssClient;
|
||||
use OSS\Core\OssException;
|
||||
|
||||
class OssService
|
||||
{
|
||||
private $accessKeyId;
|
||||
private $accessKeySecret;
|
||||
private $bucket;
|
||||
private $endpoint;
|
||||
private $ossClient;
|
||||
|
||||
public function __construct()
|
||||
{
|
||||
$this->accessKeyId = 'LTAI5tAGiH7bkVkmrniXnfkA';
|
||||
$this->accessKeySecret = 'nqklJBft6t3S0A4ZvxF4ci9ni91kmm';
|
||||
$this->bucket = 'vehicle-album';
|
||||
$this->endpoint = 'https://oss-cn-beijing.aliyuncs.com';
|
||||
$this->ossClient = new OssClient($this->accessKeyId, $this->accessKeySecret, $this->endpoint);
|
||||
}
|
||||
|
||||
/**
|
||||
* 上传图片到 OSS
|
||||
* @param string $filePath 本地文件路径
|
||||
* @param string $objectKey OSS上存储的对象名称
|
||||
* @return string 图片的 URL
|
||||
*/
|
||||
public function uploadImage($filePath, $objectKey)
|
||||
{
|
||||
try {
|
||||
// 上传文件到 OSS
|
||||
$this->ossClient->uploadFile($this->bucket, $objectKey, $filePath);
|
||||
// 构造图片的私有 URL
|
||||
$url = $this->generatePrivateUrl($objectKey);
|
||||
return $url;
|
||||
} catch (OssException $e) {
|
||||
// 错误处理
|
||||
throw new \RuntimeException('OSS Error: ' . $e->getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 生成图片的私有访问 URL
|
||||
* @param string $objectKey
|
||||
* @return string
|
||||
*/
|
||||
public function generatePrivateUrl($objectKey, $expireTime = 3600)
|
||||
{
|
||||
// 生成 OSS 私有 URL(有效期为 3600 秒)
|
||||
return $this->ossClient->signUrl($this->bucket, $objectKey, $expireTime);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user