как проверить файл с помощью ngx-file-drop в angular 5+?

Я использую «ngx-file-drop» на Angular 6.

<file-drop headertext="Drop files here" (onFileDrop)="dropped($event)" 
             (onFileOver)="fileOver($event)" (onFileLeave)="fileLeave($event)" multiple>
                 <span>optional content (don't set headertext then)</span>
             </file-drop>

И файл компонента

public dropped(event: UploadEvent) {
    this.files = event.files;
    for (const droppedFile of event.files) {

      // Is it a file?
      if (droppedFile.fileEntry.isFile) {
        const fileEntry = droppedFile.fileEntry as FileSystemFileEntry;
        fileEntry.file((file: File) => {

          // Here you can access the real file
          // console.log("dropfile_file"+ droppedFile.relativePath, file);

          this.drop_files.push(file);
          console.log(this.drop_files);



        });
      } else {
        // It was a directory (empty directories are added, otherwise only files)
        const fileEntry = droppedFile.fileEntry as FileSystemDirectoryEntry;
        console.log("file_entry"+ droppedFile.relativePath, fileEntry);
      }
    }
  }

  public fileOver(event){
    console.log("file_over"+event);
  }

  public fileLeave(event){
    console.log("file_leave"+event);
  }

Я понятия не имею, как проверить файл с помощью ngx-file-drop.

Есть ли какой-либо подход в ngx-file-drop для проверки файла? пожалуйста помоги.

Спасибо,


person Shubham Azad    schedule 25.10.2018    source источник
comment
Я также использую эту библиотеку, пытаясь сделать нечто подобное. Я вижу в документах, что есть входной параметр accept, который передается вплоть до базового тега ‹input›, но я не вижу, чтобы это что-то делало с функцией перетаскивания. У меня есть набор параметров accept=png, как в документах, и я все еще могу перетаскивать любой файл. Это ожидаемая функциональность с этой библиотекой? Мне было интересно, есть ли готовое решение и способ избежать синтаксического анализа расширения файла при удалении ответов, как указано ниже.   -  person Jake    schedule 20.03.2019


Ответы (2)


Я заставил это работать так:

public dropped(event: UploadEvent) {
    if (event.files.length > 1) {
        alert("impossible de rajouter plus d'un document à la fois");
    } else {
        this.verifierEnvoyerDocument(event.files[0]);
    }
}

verifierEnvoyerDocument(droppedFile: UploadFile) {
    this.file = droppedFile;
    // Is it a file and is it allowed?
    if (droppedFile.fileEntry.isFile && this.isFileAllowed(droppedFile.fileEntry.name)) {
        const fileEntry = droppedFile.fileEntry as FileSystemFileEntry;
        fileEntry.file((file: File) => {
            console.log('isFile :', file.name);
            console.log(droppedFile.relativePath, file);
            this.envoyerDocument(droppedFile.relativePath, file);
        });
    } else {
        alert("Seul les fichiers au format '.doc', '.docx', '.ppt', '.pptx', '.pdf' sont accepté.");
    }
}

isFileAllowed(fileName: string) {
    let isFileAllowed = false;
    const allowedFiles = ['.doc', '.docx', '.ppt', '.pptx', '.pdf'];
    const regex = /(?:\.([^.]+))?$/;
    const extension = regex.exec(fileName);
    if (isDevMode()) {
        console.log('extension du fichier : ', extension);
    }
    if (undefined !== extension && null !== extension) {
        for (const ext of allowedFiles) {
            if (ext === extension[0]) {
                isFileAllowed = true;
            }
        }
    }
    return isFileAllowed;
}

Надеюсь, это поможет кому-то.

person J.P    schedule 21.02.2019

import { UploadEvent, UploadFile, FileSystemFileEntry, FileSystemDirectoryEntry } from 'ngx-file-drop';




public dropped(event: UploadEvent) {
    let droppedFile = event.files[0];
      if (droppedFile.fileEntry.isFile) {
        const fileEntry = droppedFile.fileEntry as FileSystemFileEntry;
        fileEntry.file((file: File) => {
          this.file = file;
        });
    }
  }

в нескольких циклах event.files

person Eassa Nassar    schedule 18.03.2019