错误:类型'string |不存在属性'split' ArrayBuffer”。类型“ ArrayBuffer”上不存在属性“ split”

时间:2018-08-27 04:32:45

标签: angular split base64

当我从angular 6项目上载图像时,我想按照教程将图像转换为Base64。当我按下提交按钮时,我可以获取输出值:“ base64代码”,也可以通过使用“将Base64转换为图像”将代码转换为图像来获取同一图像。 但是在代码中,它显示“类型'string | ArrayBuffer'上不存在属性'split'。类型'ArrayBuffer'上不存在属性'split'。”通过在红色下划线强调错误。我也尝试过similar question & answers 。但是它无法消除错误。

我的代码是

import {Component, ElementRef, ViewChild} from '@angular/core';
import {FormBuilder, FormGroup, Validators} from "@angular/forms";

@Component({
  selector: 'base64-upload',
  templateUrl: './base64-upload.component.html'
})
export class Base64UploadComponent {
  form: FormGroup;
  loading: boolean = false;


  @ViewChild('fileInput') fileInput: ElementRef;

  constructor(private fb: FormBuilder) {
    this.createForm();
  }

  createForm() {
    this.form = this.fb.group({
      name: ['', Validators.required],
      avatar: null
    });
  }

  onFileChange(event) {
    let reader = new FileReader();
    if(event.target.files && event.target.files.length > 0) {
      let file = event.target.files[0];
      reader.readAsDataURL(file);
      reader.onload = () => {
        this.form.get('avatar').setValue({
          filename: file.name,
          filetype: file.type,
          value: reader.result.split(',')[1]
        })
      };
    }
  }

  onSubmit() {
    const formModel = this.form.value;
    this.loading = true;
    // this.http.post('apiUrl', formModel)
    setTimeout(() => {
      console.log(formModel);
      alert('done!');
      this.loading = false;
    }, 1000);
  }

  clearFile() {
    this.form.get('avatar').setValue(null);
    this.fileInput.nativeElement.value = '';
  }

}

我的html代码是

<form [formGroup]="form" (ngSubmit)="onSubmit()">
  <div class="form-group">
    <label for="name">Name</label>
    <input type="text" class="form-control" id="name" placeholder="Bob" formControlName="name">
  </div>

  <div class="form-group">
    <label for="avatar">Avatar</label>
    <input type="file" id="avatar" (change)="onFileChange($event)"  #fileInput>
    <button type="button" class="btn btn-sm btn-default" (click)="clearFile()">clear file</button>
  </div>

  <button type="submit" [disabled]="form.invalid || loading" 
                        class="btn btn-success">Submit <i class="fa fa-spinner fa-spin fa-fw" *ngIf="loading"></i>
  </button>

</form>

1 个答案:

答案 0 :(得分:0)

您必须转换拆分值:将...替换为要拆分的值

(<string> ... ).split(',')[1]