forceDelete(); $content = Base::json2array($this->content ?: []); if (str_starts_with($content['url'], 'uploads/')) { $path = public_path($content['url']); if (file_exists($path)) { @unlink($path); } } } /** * 转预览地址 * @param array $array * @return string */ public static function toPreviewUrl($array) { $fileExt = $array['ext']; $fileName = $array['name']; $filePath = $array['path']; $name = Base::rightDelete($fileName, ".{$fileExt}") . ".{$fileExt}"; $key = urlencode(Base::urlAddparameter($filePath, [ 'name' => $name, 'ext' => $fileExt ])); return Base::fillUrl("online/preview/{$name}?key={$key}&version=" . Base::getVersion() . "&__=" . Timer::msecTime()); } /** * 转预览地址 * @param File $file * @param $content * @return string */ public static function formatPreview($file, $content) { $content = Base::json2array($content ?: []); $filePath = $content['url']; if (in_array($file->type, ['word', 'excel', 'ppt'])) { if (empty($content)) { $filePath = 'assets/office/empty.' . str_replace(['word', 'excel', 'ppt'], ['docx', 'xlsx', 'pptx'], $file->type); } } return self::toPreviewUrl([ 'ext' => $file->ext, 'name' => $file->name, 'path' => $filePath, ]); } /** * 获取格式内容(或下载) * @param $file * @param $content * @param $download * @return array|StreamedResponse */ public static function formatContent($file, $content, $download = false) { $name = $file->ext ? "{$file->name}.{$file->ext}" : null; $content = Base::json2array($content ?: []); if (in_array($file->type, ['word', 'excel', 'ppt'])) { if (empty($content)) { $filePath = public_path('assets/office/empty.' . str_replace(['word', 'excel', 'ppt'], ['docx', 'xlsx', 'pptx'], $file->type)); } else { $filePath = public_path($content['url']); } return Base::DownloadFileResponse($filePath, $name); } if (empty($content)) { $content = match ($file->type) { 'document' => [ "type" => $file->ext, "content" => "", ], default => json_decode('{}'), }; abort_if($download, 403, "This file is empty."); } else { $path = $content['url']; if ($file->ext) { $res = File::formatFileData([ 'path' => $path, 'ext' => $file->ext, 'size' => $file->size, 'name' => $file->name, ]); $content = $res['content']; } else { $content['preview'] = false; } if ($download) { $filePath = public_path($path); abort_if(!isset($filePath),403, "This file not support download."); return Base::DownloadFileResponse($filePath, $name); } } return Base::retSuccess('success', [ 'content' => $content ]); } /** * 获取文件内容 * @param $id * @return self|null */ public static function idOrCodeToContent($id) { $builder = null; if (Base::isNumber($id)) { $builder = FileContent::whereFid($id); } elseif ($id) { $fileLink = FileLink::whereCode($id)->first(); if ($fileLink) { $builder = FileContent::whereFid($fileLink->file_id); } } /** @var self $fileContent */ $fileContent = $builder?->orderByDesc('id')->first(); if ($fileContent) { $fileContent->content = Base::json2array($fileContent->content ?: []); } return $fileContent; } }