这就是我目前的状况。
edit-client.component.html
<form class="form-horizontal" #clientForm="ngForm" (ngSubmit)="onSubmit(clientForm)">
...
<input type="file" (change)="fileChange($event)" placeholder="Upload file" accept=".pdf,.jpg,.jpeg,.png">
...
<input type="submit" value="Submit" class="btn btn-primary btn-block" [disabled]="!disableBtn">
edit-client.component.ts
下面是fileChange函数,通过通用API上传。
fileChange(event) {
const httpOptions = {
headers: new HttpHeaders({
'Authorization': `${this.authBearer}`,
})
};
let fileList: FileList = event.target.files;
if(fileList.length > 0) {
let file: File = this.fileList[0];
let formData:FormData = new FormData();
formData.append('files', file, file.name);
this.http.post(`${this.apiEndPoint}`, formData, httpOptions)
.subscribe( res => {
this.client.fileAttach = res[0].url;
this.client.fileAttachName = res[0].name;
})
}
}
下面是onSubmit函数,它在firebase上发布信息
onSubmit({value, valid}: {value: Client, valid: boolean}) {
console.log(this.downloadURL);
if (!valid) {
this.toasterService.pop('error', 'Error', 'Please fill the form correctly');
} else {
// Add id to client
value.id = this.id;
value.fileAttach = this.client.fileAttach;
value.fileAttachName = this.client.fileAttachName;
// update client
this.clientService.updateClient(value);
this.toasterService.pop('success', 'Sucess!', this.client.firstName + ' ' + this.client.lastName + ' Updated');
}
}
如何在单击“提交”时使文件上传,而不是在选择文件时上传?
答案 0 :(得分:1)
onChange,将其保存到类中的变量
所以而不是:
let file: File = this.fileList[0];
您这样做:
file: File;
constructor() {}
....
this.file = this.fileList[0];
Then, on submit, you do the http logic:
submit() {
let formData:FormData = new FormData();
formData.append('files', this.file, this.file.name);
this.http.post(`${this.apiEndPoint}`, formData, httpOptions)
.subscribe( res => {
this.client.fileAttach = res[0].url;
this.client.fileAttachName = res[0].name;
})
}