I'm trying to add an input with file upload to my application.
This is my view with two inputs, one text and one file:
<template>
<form class="form-horizontal" submit.delegate="doImport()">
<div class="form-group">
<label for="inputLangName" class="col-sm-2 control-label">Language key</label>
<div class="col-sm-10">
<input type="text" value.bind="languageKey" class="form-control" id="inputLangName" placeholder="Language key">
</div>
</div>
<div class="form-group">
<label for="inputFile" class="col-sm-2 control-label">Upload file</label>
<div class="col-sm-10">
<input type="file" class="form-control" id="inputFile" accept=".xlsx" files.bind="files">
</div>
</div>
<div class="form-group">
<div class="col-sm-offset-2 col-sm-10">
<button type="submit" class="btn btn-default">Do import</button>
</div>
</div>
</form>
</template>
In my webapi I have this code which I copied and pasted from here:
public class ImportLanguageController : ApiController
{
public async Task<HttpResponseMessage> Post()
{
// Check if the request contains multipart/form-data.
if (!Request.Content.IsMimeMultipartContent())
{
throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType);
}
string root = HttpContext.Current.Server.MapPath("~/App_Data");
var provider = new MultipartFormDataStreamProvider(root);
try
{
// Read the form data.
await Request.Content.ReadAsMultipartAsync(provider);
// This illustrates how to get the file names.
foreach (MultipartFileData file in provider.FileData)
{
//Trace.WriteLine(file.Headers.ContentDisposition.FileName);
//Trace.WriteLine("Server file path: " + file.LocalFileName);
}
return Request.CreateResponse(HttpStatusCode.OK);
}
catch (System.Exception e)
{
return Request.CreateErrorResponse(HttpStatusCode.InternalServerError, e);
}
}
}
At last I have my view model in Aurelia:
import {inject} from 'aurelia-framework';
import {HttpClient, json} from 'aurelia-fetch-client';
@inject(HttpClient)
export class Import {
languageKey = null;
files = null;
constructor(http){
http.configure(config => {
config
.useStandardConfiguration();
});
this.http = http;
}
doImport() {
//What goes here??
}
}
So my question is, what logic goes in my function doImport
? I'm not sure the code in my controller method in the webapi is correct, feel free to have comments on that.
This should help you get started:
Depending on the webapi response you provide (if any) you may want to use following:
One thing I should mention too is that fetch uses COR so if you get any CORS error you may need to enable them on the server side.
Here's a gist.run for the Aurelia part (posting won't work unless you change the URL): https://gist.run/?id=6aa96b19bb75f727271fb061a260f945