You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
|
|
|
|
|
<?php
|
|
|
|
|
|
|
|
|
|
|
|
namespace App\Http\Controllers\Concerns;
|
|
|
|
|
|
|
|
|
|
|
|
use Illuminate\Http\UploadedFile;
|
|
|
|
|
|
use Illuminate\Support\Facades\Storage;
|
|
|
|
|
|
use Illuminate\Support\Str;
|
|
|
|
|
|
|
|
|
|
|
|
/**
|
|
|
|
|
|
* 避免依赖 PHP fileinfo 扩展:putFile() 会用 hashName()->guessExtension(),会触发 finfo。
|
|
|
|
|
|
*/
|
|
|
|
|
|
trait StoresPublicUploadWithoutFileinfo
|
|
|
|
|
|
{
|
|
|
|
|
|
protected function storeUploadedFileAsUniqueName(UploadedFile $file, string $directory): string|false
|
|
|
|
|
|
{
|
|
|
|
|
|
$ext = strtolower($file->getClientOriginalExtension());
|
|
|
|
|
|
$name = Str::uuid()->toString();
|
|
|
|
|
|
if ($ext !== '') {
|
|
|
|
|
|
$name .= '.'.$ext;
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
Storage::disk('public')->makeDirectory($directory);
|
|
|
|
|
|
|
|
|
|
|
|
return Storage::disk('public')->putFileAs($directory, $file, $name);
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
/** 无 fileinfo 时仅用客户端声明的 MIME,避免调用 getMimeType() */
|
|
|
|
|
|
protected function mimeForUploadResponse(UploadedFile $file): string
|
|
|
|
|
|
{
|
|
|
|
|
|
if (class_exists(\finfo::class)) {
|
|
|
|
|
|
try {
|
|
|
|
|
|
return $file->getMimeType()
|
|
|
|
|
|
?: $file->getClientMimeType()
|
|
|
|
|
|
?: 'application/octet-stream';
|
|
|
|
|
|
} catch (\Throwable) {
|
|
|
|
|
|
// fallthrough
|
|
|
|
|
|
}
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
return $file->getClientMimeType() ?: 'application/octet-stream';
|
|
|
|
|
|
}
|
|
|
|
|
|
}
|