Files
KnowledgeBase/app/Http/Controllers/DocumentController.php

92 lines
2.6 KiB
PHP
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
<?php
namespace App\Http\Controllers;
use App\Models\Document;
use App\Services\DocumentPdfPreviewService;
use App\Services\DocumentService;
use Illuminate\Support\Facades\Gate;
class DocumentController extends Controller
{
protected DocumentService $documentService;
protected DocumentPdfPreviewService $pdfPreviewService;
public function __construct(
DocumentService $documentService,
DocumentPdfPreviewService $pdfPreviewService
) {
$this->documentService = $documentService;
$this->pdfPreviewService = $pdfPreviewService;
}
/**
* 预览文档的 PDF 内容
* 需求11.1, 11.3, 11.4
*
* @param Document $document
* @return \Illuminate\View\View|\Illuminate\Http\RedirectResponse
*/
public function preview(Document $document)
{
if (!Gate::allows('view', $document)) {
abort(403, '您没有权限预览此文档');
}
return view('documents.preview', [
'document' => $document,
'canPreviewPdf' => $this->pdfPreviewService->canPreview($document),
'previewPdfUrl' => $this->pdfPreviewService->previewUrl($document),
]);
}
public function previewPdf(Document $document)
{
if (! Gate::allows('view', $document)) {
abort(403, '您没有权限预览此文档');
}
try {
$path = $this->pdfPreviewService->getPreviewPath($document);
} catch (\Throwable $e) {
\Log::error('PDF 预览生成失败', [
'document_id' => $document->id,
'error' => $e->getMessage(),
]);
abort(500, 'PDF 预览生成失败:' . $e->getMessage());
}
return response()->file($path, [
'Content-Type' => 'application/pdf',
'Content-Disposition' => 'inline; filename="document-' . $document->getKey() . '.pdf"',
]);
}
/**
* 下载文档
*
* @param Document $document
* @return \Symfony\Component\HttpFoundation\StreamedResponse
*/
public function download(Document $document)
{
// 验证用户权限
if (!Gate::allows('download', $document)) {
abort(403, '您没有权限下载此文档');
}
$user = auth()->user();
try {
// 记录下载日志
$this->documentService->logDownload($document, $user);
// 返回文件下载响应
return $this->documentService->downloadDocument($document, $user);
} catch (\Exception $e) {
abort(500, '下载失败:' . $e->getMessage());
}
}
}