ExtJs标准表单提交用jsonData进行文件下载

时间:2015-03-13 21:09:57

标签: extjs asp.net-web-api extjs4

我正在尝试使用ExtJs 4.2.3从WebApi下载文件。阅读Extjs 4 downloading a file through ajax call之后,看起来我最好的选择是使用标准form.submit,但是,我的数据未按预期传递给WebApi控制器 - 使用下面的代码items来通过null。

控制器

public HttpResponseMessage Post(string exportType, List<PcAvailableComponent> items)
{
    var dataToExport = _service.ExportItems(exportType, items);
    HttpResponseMessage result = new HttpResponseMessage(HttpStatusCode.OK);
    var stream = new MemoryStream(dataToExport);
    result.Content = new StreamContent(stream);
    result.Content.Headers.ContentType =
        new MediaTypeHeaderValue("application/octet-stream");
    return result;
}

标准提交

expForm.submit({
    url: AppRootUrl + 'api/AdminDataExport?exportType=' + exportType,
    //this doesn't work
    jsonData: items,
    waitMsg: 'Generating export...',
    success: function (form, action) {
        if (typeof expWindow !== "undefined") {expWindow.close();}
    },
    failure: function(form, action) {
        Ext.Msg.alert('Failed', 'An error has occurred while generating the export: ' + JSON.parse(action.response.responseText)['ExceptionMessage']);
    }
});

Ajax提交(有效,但无法获取文件)

Ext.Ajax.request({
        url: AppRootUrl + 'api/AdminDataExport',
        params: {
            exportType: 'PricingAndCosting'
        },
        jsonData: items,
        method: 'POST',
        success: function (response) {
            expWindow.close();
            console.log("success!");
    }
});

1 个答案:

答案 0 :(得分:1)

结束放弃此控制器的Web Api,只是将JSON作为字符串传递,然后在服务器端反序列化它:

[HttpPost]
public ActionResult Index(string exportType, string items)
{
    var dataToExport = _service.ExportItems(exportType, JsonConvert.DeserializeObject<List<PcAvailableComponent>>(items));
    Response.AddHeader("Content-Disposition", "inline; filename=" + exportType + "_" + DateTime.Now.ToString("yyyyMMdd_HHmmss") + ".xlsx");
    return File(dataToExport, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
}