使用FileStreamResult时,net Core中的返回文件已损坏

时间:2018-07-17 14:42:43

标签: c# asp.net-core

我有一个返回FileStreamResult的方法来下载由NPOI创建的文件,即Excel文件。在该方法中,我使用一个示例通过FileStream在wwwroot中将文件本地保存,并且可以工作,但是当我需要返回文件并在前端下载时,下载的文件已损坏。 该文件已打开,并且包含我编写的列。 本地创建的文件可以正常打开。

这是方法:

public IActionResult DescargarRepEstacion()
{
  if (!ModelState.IsValid) {
    return StatusCode(400, ModelState);
  }
  try
  {
    var fullPath = Path.Combine(_hostingEnvironment.WebRootPath, "Formatos", "Formato Estacion.xls");
    var workBook = new HSSFWorkbook();
    var sheet = workBook.CreateSheet("Formato Estación");
    var rowIndex = 0;
    var row = sheet.CreateRow(rowIndex);
    row.CreateCell(0).SetCellValue("ID");
    row.CreateCell(1).SetCellValue("DESTINO");
    row.CreateCell(2).SetCellValue("PERMISO");
    row.CreateCell(3).SetCellValue("TERMINAL");
    rowIndex++;
    var ms = new MemoryStream();
    workBook.Write(ms);
    using (var file = new FileStream(fullPath, FileMode.Create)) {
      workBook.Write(file);
    }
    ms.Position = 0;

      return new FileStreamResult(ms, "application/vnd.ms-excel");
  }
  catch (Exception ex) {
    return StatusCode(500, ex.Message.ToString());
  }
}

在前端:

    axios.get("Formatos/DescargarEstacion", {
      headers: {
        Authorization: "Bearer " + localStorage.getItem("token"),
          'Content-Type': 'application/json',
          'Accept':'application/vnd.ms-excel',
      }
    }).then(response => {
      this.loadingDownloadEstacion = false;
      download(response.data, 'Formato Estacion.xls');
      console.log(response.data);
   //   const url = window.URL.createObjectURL(new Blob([response.data]));
   //   const link = document.createElement('a');
   //   link.href = url;
   //   link.setAttribute('download', 'Formato Estaciones.xls');
   //   document.body.appendChild(link);
   //   link.click();
    }).catch(error => {
      this.loadingDownloadEstacion = false;
      console.log(error.response);
      this.snackbar = true;
      this.textSnackbar = error.response.data;
    })

我在做什么错了?

更新白屏: enter image description here

0 个答案:

没有答案
相关问题