基本上,我有一些微小的Excel工作表,我正在上传以验证,处理,转换为业务对象,并作为JSON项返回。
我希望发生以下情况:
接下来,在控制器上,
FileProcessor
处理该文件,并使用文本字段进行实例化。如果我犯了一个简单的错误或一个复杂的错误,我对这些组件的理解还不够清楚。
注意:尝试使用按钮明确单击以发送文件,但将来我想自动执行此操作。
提交文件的表单:
<form id="fileUploadForm" action="/api/InvoiceDetailsFile/PostForProcessing" method="POST" enctype="multipart/form-data">
<input type ="hidden" name="clientSiteId" id="clientSiteId" value="3"/>
<input type="file" id="inpFile" required="required"/>
<input type ="button" id="btnSendFile" title="Send File" value="Send File"/>
</form>
上传的JavaScript(这可能非常错误):
$(document).ready(function () {
'use strict';
var btnSendFile = $("#btnSendFile");
var frmFileUpload = $("#fileUploadForm");
btnSendFile.click(function () {
console.log('send button clicked');
frmFileUpload.fileupload("send");
});
});
用于处理上传的WebAPI控制器(这可能非常错误):
[HttpPost]
public Task<List<IInvoiceDetailItem>> PostForProcessing(int clientSiteId)
{
if (!Request.Content.IsMimeMultipartContent())
{
throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType);
}
var results = new List<IInvoiceDetailItem>();
var streamProvider = new MultipartMemoryStreamProvider();
var task = Request.Content.ReadAsMultipartAsync(streamProvider).ContinueWith(t =>
{
// can I only expect 1 item here?
foreach (var item in streamProvider.Contents)
{
// if it's an Excel Sheet
if (item.IsMimeMultipartContent("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"))
{
try {
var workbook = new XLWorkbook(item.ReadAsStreamAsync().Result);
// clientSiteId here comes from form value (via constructor?), ContextUser comes from a BaseApi.
var processor =
new InvoiceProcessorFactory(clientSiteId, ContextUser)
.GetInvoiceProcessorInstance();
results = processor.ProcessInvoice(workbook).ToList();
}
catch (Exception ex)
{
throw new HttpException(Convert.ToInt32(HttpStatusCode.InternalServerError), "Well, this is a bummer. The invoice processor failed. Please see the inner exception.", ex);
}
}
}
return results;
});
return task;
}
随着我的进步,我会继续更新代码示例,但我希望能早日将其发布到那里,因为我知道我会挣扎于此。