【问题标题】:Unable to save Excel file from server无法从服务器保存 Excel 文件
【发布时间】:2020-05-04 13:33:17
【问题描述】:

我使用 .NET 中的 Aspose 库生成一个 Excel 文件,控制器返回:

public async Task<IActionResult> GetFile()
{
  byte[] bytes = null;    
  await Task.Run(() => bytes = GetBytes());    
  return new FileContentResult(bytes, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")
  {
    FileDownloadName = "Template.xlsx"
  };
}

在 React 前端,我从 redux 发送这样的请求

dispatch({
  [CALL_API]: {
    method: HttpMethod.GET,
    types: [
      types.GET_FILE_REQUEST,
      types.GET_FILE_SUCCESS,
      types.GET_FILE_ERROR,
    ],
    endpoint: `getFile`,
    useLoader: true,
    responseType: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
  },
}).then((action) => {
  if (!action.error) {
    download({
      name: fileName,
      data: action.response,
      type: action.response.type,
    });
  }
});

我收到一条错误消息,其消息是“位置 0 处 JSON 中的意外令牌 P”。在服务器上,我尝试保存文件并检查其在磁盘上的有效性,这很好。我还更改了正面和背面的响应类型值,但结果始终相同。

任何想法缺陷在哪里?

【问题讨论】:

    标签: excel asp.net-core react-redux save aspose-cells


    【解决方案1】:

    在服务器和客户端进行这些更改后,设法正确下载文件

    // server
    public async Task<IActionResult> GetFile()
    {
      Stream stream = null;    
      await Task.Run(() => stream = GetStream());    
      return File(stream, "application/octet-stream");
    }
    
    // client
    dispatch({
      [CALL_API]: {
        method: HttpMethod.GET,
        headers: {
          'Content-Type': 'application/json',
        },
        types: [
          types.GET_FILE_REQUEST,
          types.GET_FILE_SUCCESS,
          types.GET_FILE_ERROR,
        ],
        endpoint: 'getFile',
        useLoader: false,
        cacheBust: false,
        responseType: ResponseType.Blob,
      },
    }).then((data) => {
      download({
        name: fileName,
        data: data.response,
        type: data.response.type,
      });
    });
    

    【讨论】:

      猜你喜欢
      • 2014-03-27
      • 1970-01-01
      • 1970-01-01
      • 2020-07-02
      • 1970-01-01
      • 1970-01-01
      • 2014-01-07
      • 2014-08-30
      • 2022-08-22
      相关资源
      最近更新 更多