6
我創建了一個拖放虛假上傳服務。我可以記錄圖片的寬度和高度以及網址。但圖像不上傳。 問題是如果我想記錄,我上傳函數中的'img'是未定義的。我怎樣才能解決這個問題?爲什麼沒有定義?拖放圖片上傳,角度4
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;
}
}