Beautiful Open-Source Form Builder
Fix allowed file types for drag-and-drop uploads (#1335)
Julien Nahum769496b684ff
diff --git a/api/app/Rules/StorageFile.php b/api/app/Rules/StorageFile.phpindex c4f0fb96d..3a0096663 100644--- a/api/app/Rules/StorageFile.php+++ b/api/app/Rules/StorageFile.php@@ -15,6 +15,10 @@ class StorageFile implements ValidationRulepublic function __construct(public int $maxSize, public array $fileTypes = [], public ?Form $form = null){+ $this->fileTypes = array_values(array_filter(array_map(+ fn ($type) => strtolower(ltrim(trim($type), '.')),+ $fileTypes+ )));}/**diff --git a/api/tests/Unit/Rules/StorageFileTest.php b/api/tests/Unit/Rules/StorageFileTest.phpindex fcde276fb..77e85795b 100644--- a/api/tests/Unit/Rules/StorageFileTest.php+++ b/api/tests/Unit/Rules/StorageFileTest.php@@ -69,3 +69,24 @@ it('can validate file size', function () {$this->assertFalse($validator->passes('file', $invalidFile));});++it('enforces PDF-only uploads through Laravel validation', function (string $extension, bool $allowed) {+ Storage::fake();+ $uuid = Str::uuid();+ Storage::put(FileUploadPathService::getTmpFileUploadPath($uuid), str_repeat('x', 100));++ $validator = \Illuminate\Support\Facades\Validator::make([+ 'attachment' => ['document_' . $uuid . '.' . $extension],+ ], [+ 'attachment.*' => [new \App\Rules\StorageFile(1000000, [' PDF ', ''])],+ ]);++ expect($validator->passes())->toBe($allowed);+ if (!$allowed) {+ expect($validator->errors()->first('attachment.0'))->toContain('Incorrect file type');+ }+})->with([+ 'PNG bypassing the client' => ['png', false],+ 'PDF' => ['pdf', true],+ 'uppercase PDF' => ['PDF', true],+]);diff --git a/client/components/forms/heavy/FileInput.vue b/client/components/forms/heavy/FileInput.vueindex 6c7552c03..868d3e9a1 100644--- a/client/components/forms/heavy/FileInput.vue+++ b/client/components/forms/heavy/FileInput.vue@@ -156,17 +156,13 @@ export default {currentUrl() {return this.form[this.name]},+ allowedExtensions() {+ return this.accept.split(',')+ .map(extension => extension.trim().replace(/^\./, '').toLowerCase())+ .filter(Boolean)+ },acceptExtensions() {- if (!this.accept) {- return null- }- return this.accept- .split(',')- .map((i) => {- if (!i) return null- return '.' + i.trim()- })- .join(',')+ return this.allowedExtensions.map(extension => '.' + extension).join(',') || null}},@@ -273,6 +269,13 @@ export default {},uploadFileToServer(file) {if (this.disabled) return+ const extension = file.name.includes('.') ? file.name.split('.').pop().toLowerCase() : ''+ if (this.allowedExtensions.length && !this.allowedExtensions.includes(extension)) {+ useAlert().error(this.$t('forms.fileInput.invalidFileType', {+ types: this.allowedExtensions.join(', ')+ }))+ return+ }this.loading = truestoreFile(file).then((response) => {diff --git a/client/i18n/lang/ar.json b/client/i18n/lang/ar.jsonindex d40de1217..18bf525e9 100644--- a/client/i18n/lang/ar.json+++ b/client/i18n/lang/ar.json@@ -28,6 +28,7 @@"create": "إضافة"},"fileInput": {+ "invalidFileType": "نوع الملف غير صحيح. الأنواع المسموح بها: {types}","chooseFiles": "انقر لاختيار الملفات أو قم بإسقاطها هنا | انقر لاختيار ملف أو قم بإسقاطه هنا","sizeLimit": "الحد الأقصى للحجم: {count} ميجابايت لكل ملف","uploadingFile": "جاري تحميل الملف الخاص بك..."diff --git a/client/i18n/lang/bn.json b/client/i18n/lang/bn.jsonindex 32c456cef..8adb94adb 100644--- a/client/i18n/lang/bn.json+++ b/client/i18n/lang/bn.json@@ -28,6 +28,7 @@"create": "তৈরি করুন"},"fileInput": {+ "invalidFileType": "ভুল ফাইলের ধরন। অনুমোদিত ধরন: {types}","chooseFiles": "ফাইল(গুলি) বেছে নিতে ক্লিক করুন বা এখানে টেনে আনুন | একটি ফাইল বেছে নিতে ক্লিক করুন বা এখানে টেনে আনুন","sizeLimit": "সাইজ সীমা: প্রতি ফাইলে {count}MB","uploadingFile": "আপনার ফাইল আপলোড হচ্ছে..."diff --git a/client/i18n/lang/ca.json b/client/i18n/lang/ca.jsonindex 429a64a97..af55da83e 100644--- a/client/i18n/lang/ca.json+++ b/client/i18n/lang/ca.json@@ -28,6 +28,7 @@"create": "Crear"},"fileInput": {+ "invalidFileType": "Tipus de fitxer incorrecte. Només es permeten: {types}","chooseFiles": "Fes clic per triar arxiu(s) o arrossega aquí | Fes clic per triar un arxiu o arrossega aquí","sizeLimit": "Límit de mida: {count}MB per arxiu","uploadingFile": "Pujant el teu arxiu..."diff --git a/client/i18n/lang/cs.json b/client/i18n/lang/cs.jsonindex 9800c75e3..708c5850c 100644--- a/client/i18n/lang/cs.json+++ b/client/i18n/lang/cs.json@@ -28,6 +28,7 @@"create": "Vytvořit"},"fileInput": {+ "invalidFileType": "Nesprávný typ souboru. Povoleny jsou pouze: {types}","chooseFiles": "Klikněte pro výběr souboru(ů) nebo přetáhněte sem | Klikněte pro výběr souboru nebo přetáhněte sem","sizeLimit": "Limit velikosti: {count}MB na soubor","uploadingFile": "Nahrávání vašeho souboru..."diff --git a/client/i18n/lang/de.json b/client/i18n/lang/de.jsonindex ac049cfb1..43f66fc04 100644--- a/client/i18n/lang/de.json+++ b/client/i18n/lang/de.json@@ -28,6 +28,7 @@"create": "Erstellen"},"fileInput": {+ "invalidFileType": "Ungültiger Dateityp. Erlaubt sind nur: {types}","chooseFiles": "Klicken Sie, um Datei(en) auszuwählen oder hierher zu ziehen | Klicken Sie, um eine Datei auszuwählen oder hierher zu ziehen","sizeLimit": "Größenbeschränkung: {count}MB pro Datei","uploadingFile": "Ihre Datei wird hochgeladen..."diff --git a/client/i18n/lang/en.json b/client/i18n/lang/en.jsonindex b30c872af..c067ae7d5 100644--- a/client/i18n/lang/en.json+++ b/client/i18n/lang/en.json@@ -28,6 +28,7 @@"create": "Create"},"fileInput": {+ "invalidFileType": "Incorrect file type. Allowed only: {types}","chooseFiles": "Click to choose file(s) or drag here | Click to choose a file or drag here","sizeLimit": "Size limit: {count}MB per file","uploadingFile": "Uploading your file..."diff --git a/client/i18n/lang/es.json b/client/i18n/lang/es.jsonindex b290d0a28..182e108bc 100644--- a/client/i18n/lang/es.json+++ b/client/i18n/lang/es.json@@ -28,6 +28,7 @@"create": "Crear"},"fileInput": {+ "invalidFileType": "Tipo de archivo incorrecto. Solo se permiten: {types}","chooseFiles": "Haga clic para elegir archivo(s) o suéltelo(s) aquí | Haga clic para elegir un archivo o suéltelo aquí","sizeLimit": "Tamaño límite: {count}MB por archivo","uploadingFile": "Subiendo su archivo..."diff --git a/client/i18n/lang/eu.json b/client/i18n/lang/eu.jsonindex 0634ca79d..f300ff6e1 100644--- a/client/i18n/lang/eu.json+++ b/client/i18n/lang/eu.json@@ -28,6 +28,7 @@"create": "Sortu"},"fileInput": {+ "invalidFileType": "Fitxategi mota okerra. Hauek bakarrik onartzen dira: {types}","chooseFiles": "Egin klik fitxategia(k) aukeratzeko edo arrastatu hona | Egin klik fitxategia aukeratzeko edo arrastatu hona","sizeLimit": "Tamaina muga: {count}MB fitxateko","uploadingFile": "Zure fitxategia kargatzen..."diff --git a/client/i18n/lang/fr.json b/client/i18n/lang/fr.jsonindex 0f910af7e..2605d4213 100644--- a/client/i18n/lang/fr.json+++ b/client/i18n/lang/fr.json@@ -28,6 +28,7 @@"create": "Créer"},"fileInput": {+ "invalidFileType": "Type de fichier incorrect. Types autorisés : {types}","chooseFiles": "Cliquez pour choisir un/des fichier(s) ou déposez-le(s) ici | Cliquez pour choisir un fichier ou déposez-le ici","sizeLimit": "Taille limite: {count}MB par fichier","uploadingFile": "Envoi de votre fichier en cours..."diff --git a/client/i18n/lang/gl.json b/client/i18n/lang/gl.jsonindex 7880a85f8..846f189cb 100644--- a/client/i18n/lang/gl.json+++ b/client/i18n/lang/gl.json@@ -28,6 +28,7 @@"create": "Crear"},"fileInput": {+ "invalidFileType": "Tipo de ficheiro incorrecto. Só se permiten: {types}","chooseFiles": "Fai clic para escoller arquivo(s) ou arrastra aquí | Fai clic para escoller un arquivo ou arrastra aquí","sizeLimit": "Límite de tamaño: {count}MB por arquivo","uploadingFile": "Subindo o teu arquivo..."diff --git a/client/i18n/lang/hi.json b/client/i18n/lang/hi.jsonindex 8064ddf09..df5b2e07c 100644--- a/client/i18n/lang/hi.json+++ b/client/i18n/lang/hi.json@@ -28,6 +28,7 @@"create": "बनाएं"},"fileInput": {+ "invalidFileType": "गलत फ़ाइल प्रकार। केवल इनकी अनुमति है: {types}","chooseFiles": "फ़ाइलें चुनने के लिए क्लिक करें या यहां खींचें | फ़ाइल चुनने के लिए क्लिक करें या यहां खींचें","sizeLimit": "साइज़ सीमा: प्रति फ़ाइल {count}MB","uploadingFile": "आपकी फ़ाइल अपलोड हो रही है..."diff --git a/client/i18n/lang/hu.json b/client/i18n/lang/hu.jsonindex f1b5c0638..eb329d02f 100644--- a/client/i18n/lang/hu.json+++ b/client/i18n/lang/hu.json@@ -28,6 +28,7 @@"create": "Létrehozás"},"fileInput": {+ "invalidFileType": "Helytelen fájltípus. Csak ezek engedélyezettek: {types}","chooseFiles": "Kattints a fájl(ok) kiválasztásához vagy húzd ide | Kattints egy fájl kiválasztásához vagy húzd ide","sizeLimit": "Méretkorlát: {count} MB fájlonként","uploadingFile": "A fájl feltöltése folyamatban..."diff --git a/client/i18n/lang/it.json b/client/i18n/lang/it.jsonindex 25c74338d..4e617c6b3 100644--- a/client/i18n/lang/it.json+++ b/client/i18n/lang/it.json@@ -28,6 +28,7 @@"create": "Crea"},"fileInput": {+ "invalidFileType": "Tipo di file non valido. Sono consentiti solo: {types}","chooseFiles": "Clicca per scegliere i file o trascina qui | Clicca per scegliere un file o trascina qui","sizeLimit": "Limite di dimensione: {count}MB per file","uploadingFile": "Caricamento del tuo file..."diff --git a/client/i18n/lang/ja.json b/client/i18n/lang/ja.jsonindex 35f0e3c6a..927c719a8 100644--- a/client/i18n/lang/ja.json+++ b/client/i18n/lang/ja.json@@ -28,6 +28,7 @@"create": "作成"},"fileInput": {+ "invalidFileType": "ファイル形式が正しくありません。許可されている形式: {types}","chooseFiles": "クリックしてファイルを選択するか、ここにドロップしてください | クリックしてファイルを選択するか、ここにドロップしてください","sizeLimit": "サイズ制限:ファイルあたり{count}MB","uploadingFile": "ファイルをアップロード中..."diff --git a/client/i18n/lang/jv.json b/client/i18n/lang/jv.jsonindex 5435f21bc..065e3f266 100644--- a/client/i18n/lang/jv.json+++ b/client/i18n/lang/jv.json@@ -28,6 +28,7 @@"create": "Gawe"},"fileInput": {+ "invalidFileType": "Jinis berkas ora bener. Sing diidini mung: {types}","chooseFiles": "Klik kanggo milih berkas utawa seret mrene | Klik kanggo milih berkas utawa seret mrene","sizeLimit": "Watesan ukuran: {count}MB saben berkas","uploadingFile": "Berkas sampeyan lagi diunggah..."diff --git a/client/i18n/lang/ko.json b/client/i18n/lang/ko.jsonindex 9694d8078..8692cb7e4 100644--- a/client/i18n/lang/ko.json+++ b/client/i18n/lang/ko.json@@ -28,6 +28,7 @@"create": "만들기"},"fileInput": {+ "invalidFileType": "잘못된 파일 형식입니다. 허용되는 형식: {types}","chooseFiles": "파일을 선택하거나 여기로 드래그하세요 | 파일을 선택하거나 여기로 드래그하세요","sizeLimit": "크기 제한: 파일당 {count}MB","uploadingFile": "파일을 업로드하는 중..."diff --git a/client/i18n/lang/mr.json b/client/i18n/lang/mr.jsonindex e6b262649..bf81bc460 100644--- a/client/i18n/lang/mr.json+++ b/client/i18n/lang/mr.json@@ -28,6 +28,7 @@"create": "तयार करा"},"fileInput": {+ "invalidFileType": "चुकीचा फाइल प्रकार. फक्त हे प्रकार अनुमत आहेत: {types}","chooseFiles": "फाइल्स निवडण्यासाठी क्लिक करा किंवा येथे ड्रॅग करा | फाइल निवडण्यासाठी क्लिक करा किंवा येथे ड्रॅग करा","sizeLimit": "साइज मर्यादा: प्रति फाइल {count}MB","uploadingFile": "तुमची फाइल अपलोड होत आहे..."diff --git a/client/i18n/lang/nl.json b/client/i18n/lang/nl.jsonindex 6e7c31732..fc4beb465 100644--- a/client/i18n/lang/nl.json+++ b/client/i18n/lang/nl.json@@ -28,6 +28,7 @@"create": "Aanmaken"},"fileInput": {+ "invalidFileType": "Onjuist bestandstype. Alleen toegestaan: {types}","chooseFiles": "Klik om bestand(en) te kiezen of sleep hier | Klik om een bestand te kiezen of sleep hier","sizeLimit": "Groottelimiet: {count}MB per bestand","uploadingFile": "Je bestand wordt geüpload..."diff --git a/client/i18n/lang/pa.json b/client/i18n/lang/pa.jsonindex 3ef828001..62f267b44 100644--- a/client/i18n/lang/pa.json+++ b/client/i18n/lang/pa.json@@ -28,6 +28,7 @@"create": "ਬਣਾਓ"},"fileInput": {+ "invalidFileType": "ਗਲਤ ਫਾਈਲ ਕਿਸਮ। ਸਿਰਫ਼ ਇਹਨਾਂ ਦੀ ਇਜਾਜ਼ਤ ਹੈ: {types}","chooseFiles": "ਫਾਈਲ(ਾਂ) ਚੁਣਨ ਲਈ ਕਲਿੱਕ ਕਰੋ ਜਾਂ ਇੱਥੇ ਖਿੱਚੋ | ਫਾਈਲ ਚੁਣਨ ਲਈ ਕਲਿੱਕ ਕਰੋ ਜਾਂ ਇੱਥੇ ਖਿੱਚੋ","sizeLimit": "ਸਾਈਜ਼ ਸੀਮਾ: ਪ੍ਰਤੀ ਫਾਈਲ {count}MB","uploadingFile": "ਤੁਹਾਡੀ ਫਾਈਲ ਅਪਲੋਡ ਹੋ ਰਹੀ ਹੈ..."diff --git a/client/i18n/lang/pl.json b/client/i18n/lang/pl.jsonindex 5cb23587a..6d08be75f 100644--- a/client/i18n/lang/pl.json+++ b/client/i18n/lang/pl.json@@ -28,6 +28,7 @@"create": "Utwórz"},"fileInput": {+ "invalidFileType": "Nieprawidłowy typ pliku. Dozwolone są tylko: {types}","chooseFiles": "Kliknij, aby wybrać plik(i) lub przeciągnij tutaj | Kliknij, aby wybrać plik lub przeciągnij tutaj","sizeLimit": "Limit rozmiaru: {count}MB na plik","uploadingFile": "Przesyłanie pliku..."diff --git a/client/i18n/lang/pt.json b/client/i18n/lang/pt.jsonindex 35bd12af8..f5cdb01bf 100644--- a/client/i18n/lang/pt.json+++ b/client/i18n/lang/pt.json@@ -28,6 +28,7 @@"create": "Criar"},"fileInput": {+ "invalidFileType": "Tipo de arquivo incorreto. Permitidos apenas: {types}","chooseFiles": "Clique para escolher arquivo(s) ou arraste aqui | Clique para escolher um arquivo ou arraste aqui","sizeLimit": "Limite de tamanho: {count}MB por arquivo","uploadingFile": "Enviando seu arquivo..."diff --git a/client/i18n/lang/ru.json b/client/i18n/lang/ru.jsonindex 53ae0c622..2772ac61f 100644--- a/client/i18n/lang/ru.json+++ b/client/i18n/lang/ru.json@@ -28,6 +28,7 @@"create": "Создать"},"fileInput": {+ "invalidFileType": "Неверный тип файла. Разрешены только: {types}","chooseFiles": "Нажмите, чтобы выбрать файл(ы) или перетащите сюда | Нажмите, чтобы выбрать файл или перетащите сюда","sizeLimit": "Ограничение размера: {count}МБ на файл","uploadingFile": "Загрузка вашего файла..."diff --git a/client/i18n/lang/sk.json b/client/i18n/lang/sk.jsonindex 5138c0a97..2346fea8f 100644--- a/client/i18n/lang/sk.json+++ b/client/i18n/lang/sk.json@@ -28,6 +28,7 @@"create": "Vytvoriť"},"fileInput": {+ "invalidFileType": "Nesprávny typ súboru. Povolené sú iba: {types}","chooseFiles": "Kliknite pre výber súboru(ov) alebo pretiahnite sem | Kliknite pre výber súboru alebo pretiahnite sem","sizeLimit": "Limit veľkosti: {count}MB na súbor","uploadingFile": "Nahrávanie vášho súboru..."diff --git a/client/i18n/lang/sr.json b/client/i18n/lang/sr.jsonindex 388c71594..70b0359b7 100644--- a/client/i18n/lang/sr.json+++ b/client/i18n/lang/sr.json@@ -28,6 +28,7 @@"create": "Kreiraj"},"fileInput": {+ "invalidFileType": "Погрешан тип датотеке. Дозвољени су само: {types}","chooseFiles": "Kliknite da izaberete fajl(ove) ili prevucite ovde | Kliknite da izaberete fajl ili prevucite ovde","sizeLimit": "Ograničenje veličine: {count}MB po fajlu","uploadingFile": "Otpremanje vašeg fajla..."diff --git a/client/i18n/lang/sv.json b/client/i18n/lang/sv.jsonindex 2b85c0ac2..8e6c52326 100644--- a/client/i18n/lang/sv.json+++ b/client/i18n/lang/sv.json@@ -28,6 +28,7 @@"create": "Skapa"},"fileInput": {+ "invalidFileType": "Felaktig filtyp. Endast följande tillåts: {types}","chooseFiles": "Klicka för att välja fil(er) eller dra hit | Klicka för att välja en fil eller dra hit","sizeLimit": "Storleksgräns: {count}MB per fil","uploadingFile": "Laddar upp din fil..."diff --git a/client/i18n/lang/ta.json b/client/i18n/lang/ta.jsonindex 9c9941650..46626b013 100644--- a/client/i18n/lang/ta.json+++ b/client/i18n/lang/ta.json@@ -28,6 +28,7 @@"create": "உருவாக்கு"},"fileInput": {+ "invalidFileType": "தவறான கோப்பு வகை. அனுமதிக்கப்பட்டவை: {types}","chooseFiles": "கோப்புகளைத் தேர்ந்தெடுக்க கிளிக் செய்யவும் அல்லது இங்கே இழுக்கவும் | கோப்பைத் தேர்ந்தெடுக்க கிளிக் செய்யவும் அல்லது இங்கே இழுக்கவும்","sizeLimit": "அளவு வரம்பு: ஒரு கோப்புக்கு {count}MB","uploadingFile": "உங்கள் கோப்பு பதிவேற்றப்படுகிறது..."diff --git a/client/i18n/lang/te.json b/client/i18n/lang/te.jsonindex d4c3a5bef..41a622b5b 100644--- a/client/i18n/lang/te.json+++ b/client/i18n/lang/te.json@@ -28,6 +28,7 @@"create": "సృష్టించండి"},"fileInput": {+ "invalidFileType": "చెల్లని ఫైల్ రకం. అనుమతించబడినవి: {types}","chooseFiles": "ఫైల్(లు) ఎంచుకోవడానికి క్లిక్ చేయండి లేదా ఇక్కడ డ్రాగ్ చేయండి | ఫైల్ ఎంచుకోవడానికి క్లిక్ చేయండి లేదా ఇక్కడ డ్రాగ్ చేయండి","sizeLimit": "పరిమాణ పరిమితి: ప్రతి ఫైల్కు {count}MB","uploadingFile": "మీ ఫైల్ అప్లోడ్ అవుతోంది..."diff --git a/client/i18n/lang/tr.json b/client/i18n/lang/tr.jsonindex 3e27cc098..2cddc3e0d 100644--- a/client/i18n/lang/tr.json+++ b/client/i18n/lang/tr.json@@ -28,6 +28,7 @@"create": "Oluştur"},"fileInput": {+ "invalidFileType": "Geçersiz dosya türü. Yalnızca izin verilenler: {types}","chooseFiles": "Dosyaları seçmek için tıklayın veya buraya sürükleyin | Dosya seçmek için tıklayın veya buraya sürükleyin","sizeLimit": "Boyut sınırı: dosya başına {count}MB","uploadingFile": "Dosyanız yükleniyor..."diff --git a/client/i18n/lang/uk.json b/client/i18n/lang/uk.jsonindex 272fe5eb6..59f9583cd 100644--- a/client/i18n/lang/uk.json+++ b/client/i18n/lang/uk.json@@ -28,6 +28,7 @@"create": "Створити"},"fileInput": {+ "invalidFileType": "Неправильний тип файлу. Дозволено лише: {types}","chooseFiles": "Клацніть, щоб вибрати файл(и), або перетягніть сюди | Клацніть, щоб вибрати файл або перетягніть сюди","sizeLimit": "Обмеження розміру: {count}MB на файл","uploadingFile": "Завантаження вашого файлу..."diff --git a/client/i18n/lang/ur.json b/client/i18n/lang/ur.jsonindex d74e62869..54d10be61 100644--- a/client/i18n/lang/ur.json+++ b/client/i18n/lang/ur.json@@ -28,6 +28,7 @@"create": "بنائیں"},"fileInput": {+ "invalidFileType": "فائل کی قسم غلط ہے۔ صرف ان کی اجازت ہے: {types}","chooseFiles": "فائل(یں) منتخب کرنے کے لیے کلک کریں یا یہاں کھینچیں | فائل منتخب کرنے کے لیے کلک کریں یا یہاں کھینچیں","sizeLimit": "سائز کی حد: فی فائل {count}MB","uploadingFile": "آپ کی فائل اپلوڈ ہو رہی ہے..."diff --git a/client/i18n/lang/vi.json b/client/i18n/lang/vi.jsonindex 11ac6420f..8b9d88f9f 100644--- a/client/i18n/lang/vi.json+++ b/client/i18n/lang/vi.json@@ -28,6 +28,7 @@"create": "Tạo"},"fileInput": {+ "invalidFileType": "Loại tệp không hợp lệ. Chỉ cho phép: {types}","chooseFiles": "Nhấp để chọn tệp hoặc kéo vào đây | Nhấp để chọn tệp hoặc kéo vào đây","sizeLimit": "Giới hạn kích thước: {count}MB mỗi tệp","uploadingFile": "Đang tải tệp của bạn lên..."diff --git a/client/i18n/lang/zh.json b/client/i18n/lang/zh.jsonindex 22d740c28..dd39af172 100644--- a/client/i18n/lang/zh.json+++ b/client/i18n/lang/zh.json@@ -28,6 +28,7 @@"create": "创建"},"fileInput": {+ "invalidFileType": "文件类型不正确。仅允许:{types}","chooseFiles": "点击选择文件或将文件拖放到此处 | 点击选择文件或将文件拖放到此处","sizeLimit": "大小限制:每个文件 {count}MB","uploadingFile": "正在上传您的文件..."diff --git a/client/test/nuxt/file-input.spec.ts b/client/test/nuxt/file-input.spec.tsnew file mode 100644index 000000000..753d15a65--- /dev/null+++ b/client/test/nuxt/file-input.spec.ts@@ -0,0 +1,98 @@+import { beforeEach, describe, expect, it, vi } from 'vitest'+import { flushPromises, mount } from '@vue/test-utils'+import { mockNuxtImport } from '@nuxt/test-utils/runtime'+import FileInput from '../../components/forms/heavy/FileInput.vue'+import { storeFile } from '../../lib/file-uploads.js'++const { showError } = vi.hoisted(() => ({ showError: vi.fn() }))+mockNuxtImport('useAlert', () => () => ({ error: showError }))+vi.mock('../../lib/file-uploads.js', () => ({ storeFile: vi.fn() }))+vi.mock('../../components/forms/heavy/components/CameraUpload.vue', () => ({ default: { template: '<div />' } }))++function createWrapper(props = {}) {+ return mount(FileInput, {+ props: { name: 'attachment', modelValue: [], accept: 'pdf', ...props },+ global: {+ mocks: { $t: (key, params) => params?.types ? `Allowed only: ${params.types}` : key },+ stubs: {+ InputWrapper: { template: '<div><slot /></div>' },+ UploadedFile: true,+ UButton: true,+ ClientOnly: { template: '<div><slot /></div>' },+ },+ },+ })+}++function fileList(files) {+ return { length: files.length, item: index => files[index] }+}++describe('FileInput allowed file types', () => {+ beforeEach(() => {+ vi.clearAllMocks()+ vi.mocked(storeFile).mockResolvedValue({ uuid: 'upload-id', extension: 'pdf' })+ })++ it.each(['drop', 'picker'])('rejects a PNG from the %s before uploading', async (source) => {+ const wrapper = createWrapper()+ await flushPromises()+ const files = fileList([new File(['image'], 'image.png', { type: 'image/png' })])++ if (source === 'drop') {+ await wrapper.get('[role="button"]').trigger('drop', { dataTransfer: { files } })+ } else {+ Object.defineProperty(wrapper.get('input').element, 'files', { value: files })+ await wrapper.get('input').trigger('change')+ }++ expect(storeFile).not.toHaveBeenCalled()+ expect(showError).toHaveBeenCalledWith('Allowed only: pdf')+ expect(wrapper.vm.files).toEqual([])+ expect(wrapper.vm.loading).toBe(false)+ })++ it('uploads an allowed dropped file with uppercase extension and empty MIME type', async () => {+ const wrapper = createWrapper({ accept: ' PDF , , .jpg ' })+ await flushPromises()+ const file = new File(['document'], 'document.PDF')+ expect(wrapper.get('input').attributes('accept')).toBe('.pdf,.jpg')++ await wrapper.get('[role="button"]').trigger('drop', { dataTransfer: { files: fileList([file]) } })+ await flushPromises()++ expect(storeFile).toHaveBeenCalledWith(file)+ expect(wrapper.vm.files).toHaveLength(1)+ expect(showError).not.toHaveBeenCalled()+ })++ it('keeps accepted files when a mixed batch contains a rejected file', async () => {+ const wrapper = createWrapper()+ await flushPromises()+ const pdf = new File(['document'], 'document.pdf')+ const png = new File(['image'], 'image.png')+ await wrapper.get('[role="button"]').trigger('drop', { dataTransfer: { files: fileList([pdf, png]) } })+ await flushPromises()++ expect(storeFile).toHaveBeenCalledTimes(1)+ expect(wrapper.vm.files[0].file.name).toBe('document.pdf')+ expect(showError).toHaveBeenCalledOnce()+ })++ it('allows all extensions when restrictions are blank', async () => {+ const wrapper = createWrapper({ accept: ' , ' })+ await flushPromises()+ const file = new File(['data'], 'README')+ await wrapper.get('[role="button"]').trigger('drop', { dataTransfer: { files: fileList([file]) } })+ expect(storeFile).toHaveBeenCalledWith(file)+ expect(showError).not.toHaveBeenCalled()+ })++ it('rejects camera files using the same restrictions', async () => {+ const wrapper = createWrapper({ cameraUpload: true })+ await flushPromises()+ wrapper.vm.cameraFileUpload(new File(['image'], 'camera.png'))+ expect(storeFile).not.toHaveBeenCalled()+ expect(showError).toHaveBeenCalledOnce()+ })+})