I am working with a controller that includes a Create
action. The main purpose of this action is to receive a name and data from a file form, and then return a list of files using the IndexViewModel
.
public class HomeController : Controller
{
static List<Models.File> files = new List<Models.File>();
public HomeController() { }
[HttpGet]
public IActionResult Index() => View(new IndexViewModel { Files = files });
[HttpGet]
public IActionResult Create() => View();
[HttpPost]
public IActionResult Create(IFormFile file)
{
var filename =
ContentDispositionHeaderValue.Parse(file.ContentDisposition)
.FileName;
using (var reader = new StreamReader(file.OpenReadStream()))
{
var content = reader.ReadToEnd();
files.Add(new Models.File { Name = filename, Data = content });
}
return RedirectToAction(nameof(Index));
}
}
While using a form in static html, the server receives the data without any issues. However, when the same form is used within an Angular2 template, it fails to work properly.
import {Component} from 'angular2/core';
import {File} from './file';
@Component({
selector: 'listfile',
template: `
<form method="post" asp-action="Index" asp-controller="Api/File" enctype="multipart/form-data">
<input type="file" name="files" #newFile (keyup.enter)="addFile(newFile.value)"
(blur)="addFile(newFile.value); newFile.value='' ">
<input type="submit" value="Upload" />
</form>
<table class="table">
<th>id</th><th>name</th>
<tr *ngFor="#file of files">
<td>{{file.id}}</td>
<td>{{file.name}}</td>
</tr>
</table>
`
})
export class ListFileComponent {
files = [
new File(1, 'file1'),
new File(2, 'file2')
];
addFile(newFile: string) {
if (newFile) {
this.files.push(new File(this.files.length + 1, newFile.split(/(\\|\/)/g).pop()))
}
}
falert(value) {
alert(value);
}
}