将Excelfile upload到Web API

我正在尝试上传一个excel文件到我的WebApi和DO STUFF的内容。 我有extJs部分通过完成上传button发送文件。 (代码如下)

我的问题是我不知道如何build立webApi部分来处理excel文件。 我猜我必须有一个HttpPost。

假WebApi:

public string SampleUploadFile() { return _repo.UploadFile(); } 

Extjs代码:

 xtype: 'form', //renderTo: 'fi-form', //(5) fileUpload: true, //(1) width: 500, frame: true, title: 'Position Sheet Upload Form', bodyPadding: '10 10 0', //bodyStyle: 'padding: 10px 10px 0 10px;', defaults: { anchor: '100%', allowBlank: false, msgTarget: 'side', labelWidth: 50 }, //labelWidth: 50, items: [{ xtype: 'fileuploadfield', emptyText: 'Select an image', fieldLabel: 'Image', name: 'file', //(2) buttonText: 'Choose a file' }], buttons: [{ text: 'Save', handler: function () { if (this.up('form').getForm().isValid()) { this.up('form').getForm().submit({ url: 'Home/Upload', waitMsg: 'Uploading your file...', success: function (form, o) //(3) { Ext.Msg.show({ title: 'Result', msg: o.result.result, buttons: Ext.Msg.OK, icon: Ext.Msg.INFO }); }, failure: function (form, o) //(4) { Ext.Msg.show({ title: 'Result', msg: o.result.error, buttons: Ext.Msg.OK, icon: Ext.Msg.ERROR }); } }); } } }] 

有谁知道如何做到这一点? 我应该有一个参数是文件?

你可以像这样处理文件:

 public void UploadFile(HttpRequestMessage request) { HttpContext context = HttpContext.Current; HttpPostedFile postedFile = context.Request.Files["file"]; // ... } 

另一种可能的解 Web API方法使用ClosedXML nuget包来读取包含excel内容的stream:

 using ClosedXML.Excel; public async void UploadFile() { var context = HttpContext.Current; if (!Request.Content.IsMimeMultipartContent()) { throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType); } var provider = new MultipartMemoryStreamProvider(); await Request.Content.ReadAsMultipartAsync(provider); foreach (HttpContent ctnt in provider.Contents) { //now read individual part into STREAM var stream = await ctnt.ReadAsStreamAsync(); if (stream.Length != 0) { //handle the stream here using (XLWorkbook excelWorkbook = new XLWorkbook(stream)) { var name = excelWorkbook.Worksheet(1).Name; } } } }