UploadForm.php 2.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102
  1. <?php
  2. namespace App\Livewire\UploadExam;
  3. use Livewire\Component;
  4. use Livewire\WithFileUploads;
  5. use Livewire\Attributes\On;
  6. use Filament\Notifications\Notification;
  7. use App\Jobs\ProcessOCRRecord;
  8. use Illuminate\Support\Facades\Storage;
  9. class UploadForm extends Component
  10. {
  11. use WithFileUploads;
  12. public ?string $teacherId = null;
  13. public ?string $studentId = null;
  14. public $uploadedImages = [];
  15. public bool $isUploading = false;
  16. public function mount($teacherId = null, $studentId = null)
  17. {
  18. $this->teacherId = $teacherId;
  19. $this->studentId = $studentId;
  20. }
  21. public function handleSubmit()
  22. {
  23. // 验证图片
  24. if (empty($this->uploadedImages)) {
  25. Notification::make()
  26. ->title('请上传试卷图片')
  27. ->danger()
  28. ->send();
  29. return;
  30. }
  31. $this->isUploading = true;
  32. try {
  33. // 保存图片
  34. $savedImages = [];
  35. foreach ($this->uploadedImages as $image) {
  36. $path = $image->store('exam-papers', 'public');
  37. $savedImages[] = [
  38. 'path' => $path,
  39. 'original_name' => $image->getClientOriginalName(),
  40. 'size' => $image->getSize(),
  41. ];
  42. }
  43. // 创建 OCR 记录(使用正确的字段名)
  44. $ocrRecord = \App\Models\OCRRecord::create([
  45. 'user_id' => $this->studentId,
  46. 'paper_title' => '待OCR识别',
  47. 'paper_type' => null, // OCR识别
  48. 'file_path' => $savedImages[0]['path'], // 只存储第一张图片的路径
  49. 'image_count' => count($savedImages),
  50. 'status' => 'processing',
  51. ]);
  52. // 派发 OCR 处理任务
  53. ProcessOCRRecord::dispatch($ocrRecord->id);
  54. Notification::make()
  55. ->title('上传成功')
  56. ->body('图片已上传,正在进行 OCR 识别...')
  57. ->success()
  58. ->send();
  59. // 立即跳转到 OCR 详情页,不等待识别完成
  60. $this->redirect('/admin/ocr-record-view/' . $ocrRecord->id);
  61. } catch (\Exception $e) {
  62. Notification::make()
  63. ->title('上传失败')
  64. ->body($e->getMessage())
  65. ->danger()
  66. ->send();
  67. } finally {
  68. $this->isUploading = false;
  69. }
  70. }
  71. public function resetForm()
  72. {
  73. $this->uploadedImages = [];
  74. $this->currentOcrRecordId = null;
  75. $this->ocrStatus = null;
  76. }
  77. public function removeImage($index)
  78. {
  79. unset($this->uploadedImages[$index]);
  80. $this->uploadedImages = array_values($this->uploadedImages);
  81. }
  82. public function render()
  83. {
  84. return view('livewire.upload-exam.upload-form');
  85. }
  86. }