Upload File Multipart/form-data
Document API
file.component.html
<form [formGroup]="formGroup" (ngSubmit)="onUpload()">
<input type="text" formControlName="username">
<input type="text" formControlName="email">
<input type="file" #file formControlName="file"
multiple="multiple" accept=".xls, .xlsx, .xlsm" (change)="onSelectFile(file.files)" />
<button type="submit">Upload</button>
</form>
fileComponent.ts
import { Component, OnInit } from '@angular/core';
import { FormControl, FormGroup, Validators } from '@angular/forms';
@Component({
selector: 'app-file',
templateUrl: './file.component.html',
styleUrls: ['./file.component.scss'],
})
export class fileComponent implements OnInit {
public formGroup: FormGroup;
public selectedFile: any;
//public selectedFile: any[] = [];
constructor(private api: ApiService) { }
ngOnInit(): void {
this.formGroup = new FormGroup({
username: new FormControl('', Validators.required),
email: new FormControl('', Validators.required),
file: new FormControl('', Validators.required),
});
}
public get f() {
return this.formGroup.controls;
}
public onSelectFile(event): void {
if (event?.length > 0) {
const FileSize = event[0].size / 1024 / 1024; // in MB
const pattern = /\.(xls|xlsx|xlsm)$/i;
if (!pattern.test(event[0].name)) {
alert('Files must be xls, xlsx, xlsm only.');
} else if (FileSize > 5) {
alert('The file size should not exceed 5 MB.')
} else {
this.selectedFile = event[0];
//this.selectedFile.push(event[0]);
}
}
}
public onUpload(): void {
if (this.formGroup.valid && this.selectedFile) {
const formData = new FormData();
formData.append('username', this.f?.username?.value);
formData.append('email', this.f?.email?.value);
formData.append('file', this.selectedFile);
// Upload một mảng file thì dùng cách sau
//this.selectedFile.forEach(f => {
// formData.append('file', f);
//});
// Nếu post một mảng các object thì sử dụng thư viện
// npm i @octetstream/object-to-form-data --save
// hoặc sử dụng function toFormData phía dưới đây
this.api.post('/api/upload', formData).subscribe(
res => {
if (res?.success) {
alert('Success');
} else {
alert('Failed');
}
},
err => {
alert('Failed');
}
);
}
}
public toFormData = (f => f(f))(h => f => f(x => h(h)(f)(x)))(f => fd => pk => d => {
if (d instanceof Object) {
Object.keys(d).forEach(k => {
const v = d[k]
if (pk) k = `${pk}[${k}]`
if (v instanceof Object && !(v instanceof Date) && !(v instanceof File)) {
return f(fd)(k)(v)
} else {
fd.append(k, v)
}
})
}
return fd
})(new FormData())()
}
bai viet rat hay
ReplyDelete