HTML
<div class="row">
<div class="mb-6">
<label class="form-label" for="defaultFile">Upload file</label>
<input type="file" class="form-control" id="defaultFile" (change)="onChange($event)">
<hr>
<button type="button" class="btn btn-outline-theme" (click)="uploadFile()">Upload</button>
</div>
</div>
打字稿
import { Component } from '@angular/core';
import { HttpClient } from '@angular/common/http';
@Component({
selector: 'app-file-upload',
templateUrl: './file-upload.component.html',
styleUrl: './file-upload.component.scss'
})
export class FileUploadComponent {
fileToUpload: File | null = null;
constructor(private http: HttpClient) { }
onChange(event:any) {
this.fileToUpload = event.target.files[0];
}
uploadFile() {
if (!this.fileToUpload) {
alert('No file selected.');
return;
}
const formData: FormData = new FormData();
formData.append('file', this.fileToUpload, this.fileToUpload.name);
return this.http.post("<ENDPOINT TO UPLOAD THE FILE>", formData).subscribe(
(response) => {
console.log(response);
},
(error) => {
console.error(error);
}
);
}
}
文件上传工作正常。不确定清除文本框的“角度”方式是什么。 (为了保持这篇文章的简单性,我将调用 API 的代码移至组件,并删除了所有错误处理等以捕获要点。)
为了简单起见,我们可以在html中使用模板引用变量
#input
,将元素引用传递到函数中并清除值,使用input.value = null
为了简单起见,我删除了 API 调用,并将其替换为
of(true)
来模拟和 API 调用!
import { HttpClient } from '@angular/common/http';
import { Component } from '@angular/core';
import { bootstrapApplication } from '@angular/platform-browser';
import { of } from 'rxjs';
import 'zone.js';
@Component({
selector: 'app-root',
standalone: true,
template: `
<div class="row">
<div class="mb-6">
<label class="form-label" for="defaultFile">Upload file</label>
<input type="file" class="form-control" id="defaultFile" (change)="onChange($event)" #input>
<hr>
<button type="button" class="btn btn-outline-theme" (click)="uploadFile(input)">Upload</button>
</div>
</div>
`,
})
export class App {
fileToUpload: File | null = null;
constructor() {}
onChange(event: any) {
this.fileToUpload = event.target.files[0];
}
uploadFile(input: any) {
if (!this.fileToUpload) {
alert('No file selected.');
return;
}
const formData: FormData = new FormData();
formData.append('file', this.fileToUpload, this.fileToUpload.name);
return of(true).subscribe(
(response: any) => {
console.log(response);
input.value = null; // <- changed here!
},
(error: any) => {
console.error(error);
}
);
}
}
bootstrapApplication(App);