excelasp.net-corereact-reduxsaveaspose-cells

Unable to save Excel file from server


I generate an Excel file using the Aspose library in .NET and the controller returns this:

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"
  };
}

On the React front I send the request like this from 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,
    });
  }
});

I receive an error whose message is "Unexpected token P in JSON at position 0". On the server I tried saving the file and checked its validity on disk, it is fine. I also changed the response type values on the front and back but the result was always the same.

enter image description here

enter image description here

Any ideas where the flaw is?


Solution

  • Managed to download the file correctly after these changes on server and client

    // 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,
      });
    });