拖放图像上传,角度4

时间:2017-07-18 12:46:54

标签: angular typescript upload drag-and-drop angular-promise

我创建了一个拖放虚假的上传服务。我可以记录图片的宽度和高度以及网址。但是图像没有上传。 问题是如果我想记录它,我的上传功能中的'img'是未定义的。我怎样才能解决这个问题?为什么不明确?

import { Injectable } from '@angular/core';
import { Observable } from 'rxjs/Rx';

@Injectable()
export class DragNDropService {

  constructor() {
  }

  upload(formData: any) {
        const photos: any[] = formData.getAll('photos');
        const promises = photos.map((x: File) => this.getImage(x)
            .then(img => {
                return({
                id: img,
                originalName: x.name,
                fileName: x.name,
                url: img
            })}));
        return Observable.fromPromise(Promise.all(promises));
    }

    private getImage(file: File) {
        const fReader = new FileReader();
        const img = document.createElement('img');

        const readFile = new Promise((resolve, reject) => {
            fReader.onload = () => {
                resolve(img.src = fReader.result);
            }
            fReader.readAsDataURL(file);
        })

        const readImg = new Promise((resolve, reject) => {
            img.onload = () => {
                resolve(img)
            }
        })

        return Promise.all([readFile, readImg]).then(img => {
            this.getBase64Image(img)
        })
    }

    private getBase64Image(img) {
        const canvas = document.createElement('canvas');
        console.log(img[1].width)
        console.log(img[1].height)

        canvas.width = img[1].width;
        canvas.height = img[1].height;

        const ctx = canvas.getContext('2d');
        console.log(img)
        ctx.drawImage(img[1], 0, 0);

        const dataURL = canvas.toDataURL('image/png');
        return dataURL;
    }

}

1 个答案:

答案 0 :(得分:2)

我明白了,问题是我没有真正回归img。

这是我在getImage函数中的新返回语句:

sudo apt-get install ca-certificates