Posting data and file with Aurelia to ASP.NET webapi

ε祈祈猫儿з 提交于 2019-11-29 22:55:30

问题


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.


回答1:


This should help you get started:

doImport() {
  var form = new FormData()
  form.append('language', this.languageKey)
  form.append('file', this.files)
  //Edit, try this if the first line dont work for you
  //form.append('file', this.files[0])

  this.http.fetch('YOUR_URL', {
     method: 'post',
     body: form
  })
  .then( response => { 
     // do whatever here

  });
}

Depending on the webapi response you provide (if any) you may want to use following:

.then( response => response.json() )
.then( response => {
   // do whatever here
});

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



来源:https://stackoverflow.com/questions/37589636/posting-data-and-file-with-aurelia-to-asp-net-webapi

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!