This simple solution worked for me: file-upload.component.html
<div> <input type="file" #fileInput placeholder="Upload file..." /> <button type="button" (click)="upload()">Upload</button> </div>
And then load the component directly using XMLHttpRequest.
import { Component, OnInit, ViewChild } from '@angular/core'; @Component({ selector: 'app-file-upload', templateUrl: './file-upload.component.html', styleUrls: ['./file-upload.component.css'] }) export class FileUploadComponent implements OnInit { @ViewChild('fileInput') fileInput; constructor() { } ngOnInit() { } private upload() { const fileBrowser = this.fileInput.nativeElement; if (fileBrowser.files && fileBrowser.files[0]) { const formData = new FormData(); formData.append('files', fileBrowser.files[0]); const xhr = new XMLHttpRequest(); xhr.open('POST', '/api/Data/UploadFiles', true); xhr.onload = function () { if (this['status'] === 200) { const responseText = this['responseText']; const files = JSON.parse(responseText);
If you use the dotnet kernel, the parameter name must match the field name. files in this case:
[HttpPost("[action]")] public async Task<IList<FileDto>> UploadFiles(List<IFormFile> files) { return await _binaryService.UploadFilesAsync(files); }
This answer is plagiarized http://blog.teamtreehouse.com/uploading-files-ajax
Edit : After downloading, you need to clear the file download so that the user can select a new file. And instead of using XMLHttpRequest, it might be better to use fetch:
private addFileInput() { const fileInputParentNative = this.fileInputParent.nativeElement; const oldFileInput = fileInputParentNative.querySelector('input'); const newFileInput = document.createElement('input'); newFileInput.type = 'file'; newFileInput.multiple = true; newFileInput.name = 'fileInput'; const uploadfiles = this.uploadFiles.bind(this); newFileInput.onchange = uploadfiles; oldFileInput.parentNode.replaceChild(newFileInput, oldFileInput); } private uploadFiles() { this.onUploadStarted.emit(); const fileInputParentNative = this.fileInputParent.nativeElement; const fileInput = fileInputParentNative.querySelector('input'); if (fileInput.files && fileInput.files.length > 0) { const formData = new FormData(); for (let i = 0; i < fileInput.files.length; i++) { formData.append('files', fileInput.files[i]); } const onUploaded = this.onUploaded; const onError = this.onError; const addFileInput = this.addFileInput.bind(this); fetch('/api/Data/UploadFiles', { credentials: 'include', method: 'POST', body: formData, }).then((response: any) => { if (response.status !== 200) { const error = `An error occured. Status: ${response.status}`; throw new Error(error); } return response.json(); }).then(files => { onUploaded.emit(files); addFileInput(); }).catch((error) => { onError.emit(error); }); }
https://github.com/yonexbat/cran/blob/master/cranangularclient/src/app/file-upload/file-upload.component.ts
yonexbat Sep 21 '17 at 19:03 2017-09-21 19:03
source share