我是TypeScript和Angular中的新手,我想从本地加载图像,将此图像存储在变量中,并将此数据传递给另一个组件。 有人有一些例子。我尝试在JavaScript中使用示例,但不在ts中工作。在html文件中使用这个:在TypeScript中加载文件
<input type="file" name="img" multiple>
我尝试使用图像atrribute但有未定义的错误。 我应该将数组字节传递给此文件映像的其他组件或路径?
我是TypeScript和Angular中的新手,我想从本地加载图像,将此图像存储在变量中,并将此数据传递给另一个组件。 有人有一些例子。我尝试在JavaScript中使用示例,但不在ts中工作。在html文件中使用这个:在TypeScript中加载文件
<input type="file" name="img" multiple>
我尝试使用图像atrribute但有未定义的错误。 我应该将数组字节传递给此文件映像的其他组件或路径?
因为TypeScript是javaScript的超集,即使您使用的是TypeScript,也可以直接使用FileReader API。
关于输入更改事件,您可以绑定您的组件函数以使用(change)
来处理事件。 event.target.files
是一个FileList,它允许您通过索引ex:files[0]
直接访问文件,并将文件对象发送到FileReader。 这里的问题是,单个FileReader对象一次只能读取一个文件,因此在更新的示例中,递归循环遍历文件以确保一次只处理一个文件。
结果属性包含数据作为代表文件数据的URL作为base64编码的字符串。
这里是采用了棱角分明的2例组件 - 打字稿
import { Component, OnInit } from '@angular/core';
@Component({
selector: 'images',
template: `
<input type="file" name="img" multiple (change)="onChange($event)">
<div *ngFor="let fileUrl of base64Files">
<img [src]="fileUrl" />
</div>
`
})
export class ImagesComponent implements OnInit {
public base64Files: string[] = [];
private files: any[] = [];
private fileReader = new FileReader();
public onChange(event: Event) {
let files = event.target['files'];
if (event.target['files']) {
console.log(event.target['files']);
this.readFiles(event.target['files'], 0);
}
};
private readFiles(files: any[], index: number) {
let file = files[index];
this.fileReader.onload =() => {
this.base64Files.push(this.fileReader.result);
if (files[index + 1]) {
this.readFiles(files, index + 1);
} else {
console.log('loaded all files');
}
};
this.fileReader.readAsDataURL(file);
}
}
您正在查找对本地资源的http请求。
访问https://angular.io/tutorial/toh-pt6#heroes-and-http进行介绍。
将图像存储到服务中,您可以将该服务注入其他组件:https://angular.io/tutorial/toh-pt4#creating-a-hero-service。
让我知道,如果你需要更多的细节。 –
将文件路径转发给其他组件并在其中显示图像是否是一个好主意?我读过我可以从FileList ovject获取文件对象。 –
Anas Al Hamdan示例工作正常fileReader.result字符串以及如何将其显示为图像;让预览= document.querySelector('img'); preview.src = fileReader.result;如何显示多个文件? –