Angular 6-在Submit上张贴文件



这就是我目前所拥有的。

编辑客户端组件.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">

编辑客户端组件.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');
}
}

如何在单击提交时上传文件,而不是在选择文件时上传?

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;
})
}

最新更新