Angular-基于表单输入创建文件并将其提供给用户



我想构建一个组件,处理来自文本区域的用户输入,并将其作为Angular 9中的(txt(文件提供给用户。

app.component.html中的表单如下:

<form (ngSubmit)="onSubmit()" #myForm="ngForm">
<textarea name="myText" ngModel></textarea>
<input name="fileName" ngModel>
<button type="submit">Download</button>
</form>

我的app.component.ts看起来像这个

import { Component, ViewChild } from '@angular/core';
import { NgForm } from '@angular/forms';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
@ViewChild('myForm', {static: true}) myForm: NgForm;
onSubmit(){
// process this.myForm.value.myText
// serve file with this.myForm.value.fileName and myTextProcessed
}
}

如何根据表单中输入的用户输入,使用Angular创建文件并将其提供给用户?

您需要在ts文件中添加以下函数,并从submit调用它,它不会要求保存文件的位置,因为默认情况下,文件将保存在您的下载文件夹中

download() {
let file = new Blob([this.myForm.form.value.myText], {type: '.txt'});
let a = document.createElement("a"),
url = URL.createObjectURL(file);
a.href = url;
a.download = this.myForm.form.value.fileName;
document.body.appendChild(a);
a.click();
setTimeout(function() {
document.body.removeChild(a);
window.URL.revokeObjectURL(url);  
}, 0); 
}

Stacklitz示例:https://stackblitz.com/edit/angular-bpbexb

最新更新