Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Drag and drop image upload, angular 4

I created a drag and drop fake upload service. I can log the width and height of the picture as well as the url. However the image is not uploading. The problem is that the 'img' in my upload function is undefined if I want to log that. How can I fix this? Why is it undefined?

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;
    }

}
like image 956
Fanni Fulmer Avatar asked Jul 18 '17 12:07

Fanni Fulmer


1 Answers

I figured it out, the problem was that I didn't really returned img.

This is my new return statement in the getImage function:

return Promise.all([readFile, readImg]).then(img => this.getBase64Image(img))
like image 187
Fanni Fulmer Avatar answered Nov 06 '22 17:11

Fanni Fulmer