[Angular Materail] 檔案上傳範例
範例
https://stackblitz.com/edit/angular-material-file-input-with-form-field?file=src%2Fapp%2Fapp.component.ts
來源
https://forum.angular.tw/t/topic/1972/5
html
<mat-card>
<p mat-card-title>Test file input with form field</p>
<mat-divider></mat-divider>
<mat-card-content>
<br><br>
<hello [name]="name"></hello>
<mat-form-field style="width: 100%;">
<mat-label>File matInput</mat-label>
<button mat-icon-button matPrefix (click)="f_input.click()">
<mat-icon>attach_file</mat-icon>
</button>
<input type="text" readonly matInput [formControl]="display" />
<input
type="file"
multiple
hidden
#f_input
(change)="handleFileInputChange(f_input.files)"
/>
<mat-error>this field is required</mat-error>
</mat-form-field>
<br><br>
</mat-card-content>
<mat-divider></mat-divider>
<mat-card-actions align="end">
<button mat-stroked-button color="primary" [disabled]="display.invalid" (click)="handleSubmit()">
Save
</button>
</mat-card-actions>
</mat-card>
<mat-card *ngIf="file_list.length" style="margin-top: 16px;">
<mat-list>
<div mat-subheader>Submit Files ({{ file_list.length }})</div>
<mat-list-item *ngFor="let file of file_list">
<mat-icon mat-list-icon>insert_drive_file</mat-icon>
<div mat-line>{{ file }}</div>
</mat-list-item>
</mat-list>
</mat-card>
TS檔
export class AppComponent {
name = "Angular " + VERSION.major;
display: FormControl = new FormControl("", Validators.required);
file_store: FileList;
file_list: Array<string> = [];
handleFileInputChange(l: FileList): void {
this.file_store = l;
if (l.length) {
const f = l[0];
const count = l.length > 1 ? `(+${l.length - 1} files)` : "";
this.display.patchValue(`${f.name}${count}`);
} else {
this.display.patchValue("");
}
}
handleSubmit(): void {
var fd = new FormData();
this.file_list = [];
for (let i = 0; i < this.file_store.length; i++) {
fd.append("files", this.file_store[i], this.file_store[i].name);
this.file_list.push(this.file_store[i].name);
}
// do submit ajax
}
}
留言
張貼留言