无法验证我上传的所有文件

时间:2018-12-18 20:57:30

标签: angular mime-types image-upload

好吧,我正在学习如何构建均值堆栈应用程序,并尝试制作电子商务类型的应用程序。我的问题与图片上传有关。

我正在尝试一次上传多个文件,但是总是出现错误, 来自我的mime类型验证。

mime.type.validation.ts:

import { AbstractControl } from '@angular/forms';
import { Observable, Observer, of } from 'rxjs';

export const mimeType = (

  control: AbstractControl
): Promise<{ [key: string]: any }> | Observable<{ [key: string]: any }> => {
  if (typeof(control.value) === 'string') {
    return of(null);
  }
  const file = control.value as File;
  const fileReader = new FileReader();
  const frObs = Observable.create(
    (observer: Observer<{ [key: string]: any }>) => {
      fileReader.addEventListener('loadend', () => {
       let result1: any;
       let finalResult: any;
       result1 = fileReader.result;
       finalResult = result1 as ArrayBuffer;

        const arr = new Uint8Array(finalResult).subarray(0, 4);
        let header = '';
        let isValid = false;
        for (let i = 0; i < arr.length; i++) {
          header += arr[i].toString(16);
        }
        switch (header) {
          case '89504e47':
            isValid = true;
            break;
          case 'ffd8ffe0':
          case 'ffd8ffe1':
          case 'ffd8ffe2':
          case 'ffd8ffe3':
          case 'ffd8ffe8':
            isValid = true;
            break;
          default:
            isValid = false; // Or you can use the blob.type as fallback
            break;
        }
        if (isValid) {
          observer.next(null);
        } else {
          observer.next({ invalidMimeType: true });
        }
        observer.complete();
      });
      fileReader.readAsArrayBuffer(file);
    }
  );

  return frObs;
};

post-create.ts

onImagePick(event) {
let file =(event.target as HTMLInputElement).files;
 let fileArray = Array.from(file);

 if(file === undefined){return;}
  this.form.patchValue({'image' : file});
  this.form.get('image').updateValueAndValidity();    
  for(let fil of fileArray) {
  let reader = new FileReader();
  reader.onload = () => {   
  this.imagePreview.push(reader.result);
  };
  reader.readAsDataURL(fil);    
  }      
}

它给出的错误是:

错误TypeError:无法在'FileReader'上执行'readAsArrayBuffer':参数1不是'Blob'类型。

我相信在将FileList转换为单个File之前,将对模仿类型进行控制。因此,每当到达readAsArrayBuffer时,它将传递FileList的参数而不是file。但是未能发现解决问题的方法。

1 个答案:

答案 0 :(得分:0)

确实是那里的FileList!所以我将它放在for中,它停止了错误。

 onImagePick(event) {
 let file =(event.target as HTMLInputElement).files;
 let fileArray = Array.from(file);

 if(file === undefined){return;}
  for(let fil of fileArray) {
  this.form.patchValue({'image' : fil});
  this.form.get('image').updateValueAndValidity();    
  let reader = new FileReader();
  reader.onload = () => {   
  this.imagePreview.push(reader.result);
  };
  reader.readAsDataURL(fil);    
  }      
}