通常情况下,我们不会在客户端(浏览器内)直接处理文件,而是会把文件当作数据传递到服务器端处理。不过有时候,我们也会希望能通过Angular在客户端加载或者保存数据。
接下来,我们来看看如何通过Angular在客户端实现读写保存本地文件。
Angular客户端保存文件
- 通过构建
a
标签并自动化点击来实现下载
1 | saveFileWithLink() { |
- 通过
file-saver
包 - Angular预定义事件绑定上传
app.component.html
1
2
3
4
5
6
7
8
9
10
11
12<h3>
<button mat-flat-button (click)="file.click()" color="secondary">
Angular预定义事件绑定上传
</button>
<input
type="file"
id="file"
(change)="upload($event)"
style="display:none"
#file
/>
</h3>app.component.ts
1
2
3upload(event): void {
console.log(event.target.files[0].name);
}
- Angular动态绑定
change
事件上传app.component.html
1
2
3
4
5
6<h3>
<button mat-flat-button (click)="uploadDynamic()" color="secondary">
Angular动态绑定change事件
</button>
<input type="file" id="fileUpload" style="display:none" #fileUpload />
</h3>app.component.ts
1
2
3
4
5
6
7
8
9
10@ViewChild("fileUpload", {static: false}) fileUpload: ElementRef;
uploadDynamic() {
const fileUpload = this.fileUpload.nativeElement;
fileUpload.onchange = () => {
const file = fileUpload.files[0];
console.log(file.name);
};
fileUpload.click();
}Angular客户端读取文件内容
如果想要实现将读取文件内容作为函数,可以通过1
2
3
4
5
6
7readFile(file: File) {
var reader = new FileReader();
reader.onload = () => {
console.log(reader.result);
};
reader.readAsText(file);
}调用方法:1
2
3
4
5
6
7
8
9
10
11
12
13readFileContent(file: File): Promise<string> {
return new Promise<string>((resolve, reject) => {
if (!file) {
resolve('');
}
const reader = new FileReader();
reader.onload = (e) => {
const text = reader.result.toString();
resolve(text);
};
reader.readAsText(file);
});
}1
const fileContent = await readFileContent(file);
在线测试
- Angular读写客户端本地文件
引用
- Angular 11 Tutorial & Example — Upload Files with FormData, HttpClient, RxJS, and Material ProgressBar
- Angular - Read a file and parse its content
- Angular File Upload: Complete Guide