从 NET Core API 在 React 中下载 Excel:无法在“URL”上执行“createObjectURL”:重载解析失败

问题描述 投票:0回答:1

我在.NET Core中有一个WebAPI,它创建一个excel文件并将其返回给前端的函数。在 React 中构建。

API 中方法的 Sinnaure:

`[HttpGet("export")]
public IActionResult Export([FromQuery] SalespriceParams param, CancellationToken cancellationToken)
`

这是一个很大的方法,但最后它创建并返回 Excel,使用的包是 EPPlus:

`var stream = new MemoryStream();  

using (var package = new ExcelPackage(stream))
{
    var workSheet = package.Workbook.Worksheets.Add("export");
    workSheet.Cells.LoadFromCollection(result, true);
    package.Save();
}
stream.Position = 0;                  

return File(stream, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", "export.xlsx");`

但是在 React 中保存文件失败。我尝试过 POST 和 GET 方法,但下载时出现错误,或者参数未传递到后端,并且数据未过滤并返回所有行:

这是我方法的最新版本:

`
const Excel = {
    export: (params: URLSearchParams) => {
        axios.get(`/excel/export`, {params: {params}, headers: {responseType: blob'}}).then((responseBody) => {      
            const link = document.createElement('a');
            const url = URL.createObjectURL(responseBody.data);
            console.log(url);
            link.href = url;
            const date = new Date();
            link.download = 'export.xlsx';
            link.click();       
        })
    }
}`

最新错误消息:无法在“URL”上执行“createObjectURL”:重载解析失败。此外,SalespriceParams param do 为空,仅包含默认值。

在这种情况下,我认为响应不被识别为斑点。

我在后端和前端都从 GET 请求切换为 POST 请求。 在下载之前,我还尝试使用 new Blob(...) 从结果创建一个 blob。

目标是将Excel文件下载到本地计算机。

如果我省略responseType: 'blob',所有参数都会传递到后端

export: (params: URLSearchParams) => {
    axios.get(`/excel/export`, {params}).then((responseBody) => {      
        const link = document.createElement('a');
        const url = URL.createObjectURL(responseBody.data);
        console.log(url);
        link.href = url;
        const date = new Date();
        link.download = 'export.xlsx';
        ink.click();       
    })
}

但是下载再次失败,并出现相同的错误(无法在“URL”上执行“createObjectURL”),因为现在没有迹象表明它将是一个 blob。

reactjs .net-core download asp.net-core-webapi
1个回答
0
投票

您正在设置

headers: {responseType: blob'}
,这似乎不正确。要使其工作,您应该作为 Axios
responseType
选项的一部分提供,而不是在
headers
下。

以下是您可以尝试的示例代码:

const Excel = {
  export: (params) => {
    axios.get(`/excel/export`, {
      params: params,
      responseType: 'blob' 
    }).then((response) => {
      const url = window.URL.createObjectURL(new Blob([response.data]));
      const link = document.createElement('a');
      link.href = url;
      link.setAttribute('download', 'export.xlsx'); 
      document.body.appendChild(link);
      link.click();
      window.URL.revokeObjectURL(url); 
    }).catch(error => {
      console.error('Download error:', error);
    });
  }
};

确保 API 方法使用正确的参数绑定。您配置 URLSearchParams 的方式可能与

[FromQuery]
不兼容。确保您的查询参数在两端命名一致,如下所示:

const params = new URLSearchParams({
  startDate: '2021-01-01',
  endDate: '2021-12-31'
});
Excel.export(params);

这将生成一个使用查询字符串构造的 URL,例如:

`/excel/export?startDate=2021-01-01&endDate=2021-12-31`

在服务器端,确保

SalespriceParams
可以从查询字符串与其属性的公共设置器绑定:

public class SalespriceParams
{
    public DateTime StartDate { get; set; }
    public DateTime EndDate { get; set; }
    // Other properties...
}

确保您的 .NET Core API 可以从查询字符串绑定

SalespriceParams

© www.soinside.com 2019 - 2024. All rights reserved.