0

我正在尝试在 MVC 控制器方法中使用 Jquery Ajax 调用和 File(bytes, contentType, fileName) 下载 excel 文件,并在服务器上托管项目时遇到错误。

错误截图

但我的代码在本地机器上运行良好。请在这里阐明一下。

索引.html:

  $.ajax({
                    url: "/reporting/GenerateReport",
                    method: "POST",
                    data: JSON.stringify(selectedIds),
                    datatype: "json",
                    contentType: 'application/json; charset=utf-8',
                    success: function (data) {
                       
                        window.location = '/reporting/DownloadExcel?fileGuid=' + data.FileGuid
                            + '&filename=' + data.FileName;
                    }
                });

控制器方法:

    public async Task<ActionResult> GenerateReport(int[] selectedIDs)
    {
        string handle = Guid.NewGuid().ToString();

        using (var client =ArchAppHttpClient.GetClient())
        {
            var serializedProduct = JsonConvert.SerializeObject(selectedIDs); 
            var content = new StringContent(serializedProduct, Encoding.UTF8, "application/json");
            var responseTask = await client.PostAsync("/api/reporting", content);
            byte[] result=null;
            if (responseTask.IsSuccessStatusCode)
            {
                var readTask = responseTask.Content.ReadAsAsync<byte[]>();
                readTask.Wait();
                result = readTask.Result;
            }
            TempData[handle] = result;

        }

        return new JsonResult()
        {
            Data = new { FileGuid = handle, FileName = "Details.xlsx" }
        };
    }

    public ActionResult DownloadExcel(string fileGuid, string fileName)
    {
        if (TempData[fileGuid] != null)
        {
            byte[] data = TempData[fileGuid] as byte[];
            return File(data, "application/vnd.ms-excel", fileName);
        }
        else
            return new EmptyResult();
        }
    }
4

0 回答 0