init
This commit is contained in:
65
app/Api/Controllers/StorageController.php
Normal file
65
app/Api/Controllers/StorageController.php
Normal file
@@ -0,0 +1,65 @@
|
||||
<?php
|
||||
|
||||
namespace App\Api\Controllers;
|
||||
|
||||
use App\Models\Storage as StorageModel;
|
||||
use Illuminate\Http\JsonResponse;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Support\Facades\Config;
|
||||
use Illuminate\Support\Facades\File;
|
||||
use Illuminate\Support\Facades\Storage;
|
||||
|
||||
class StorageController extends Controller
|
||||
{
|
||||
private string $uploadPath;
|
||||
|
||||
public function __construct()
|
||||
{
|
||||
$this->uploadPath = Config::get('storage.upload_path').date('/Y/m/d');
|
||||
}
|
||||
|
||||
public function upload(Request $request): JsonResponse
|
||||
{
|
||||
$upload = $request->file('upload');
|
||||
|
||||
$size = File::size($upload->path());
|
||||
|
||||
if ($size > Config::get('storage.max_upload_size')) {
|
||||
return $this->failed('超过最大允许上传大小', 422);
|
||||
}
|
||||
|
||||
$exists = true;
|
||||
$hash = File::hash($upload->path());
|
||||
|
||||
$existFile = StorageModel::where('driver', Config::get('filesystems.default'))->where('hash', $hash)->first();
|
||||
|
||||
if ($existFile) {
|
||||
$fullName = $existFile->path;
|
||||
} else {
|
||||
$path = $this->uploadPath;
|
||||
$fileName = $hash.'.'.$upload->getClientOriginalExtension();
|
||||
$fullName = $path.'/'.$fileName;
|
||||
|
||||
$uploaded = Storage::putFileAs($path, $upload, $fileName);
|
||||
|
||||
if (! $uploaded) {
|
||||
return $this->failed('文件上传失败', 422);
|
||||
}
|
||||
$exists = false;
|
||||
StorageModel::create([
|
||||
'hash' => $hash,
|
||||
'driver' => Config::get('filesystems.default'),
|
||||
'type' => $upload->getClientMimeType(),
|
||||
'size' => $size,
|
||||
'path' => $fullName,
|
||||
]);
|
||||
}
|
||||
|
||||
return $this->success([
|
||||
'exists' => $exists,
|
||||
'size' => $size,
|
||||
'path' => $fullName,
|
||||
'url' => Storage::url($fullName),
|
||||
]);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user