asp.net core webapi 向前端返回一个文件

后端接口返回文件

[Authorization] //给下载模版添加权限
[HttpGet]
public IActionResult DownloadTemplate()
{
    //AppContext.BaseDirectory 用于获取项目根目录
    var filePath = $"{AppContext.BaseDirectory}/MyStaticFiles/取货模板.csv";
    if (!System.IO.File.Exists(filePath))
    {
        return new JsonResult("模板文件不存在!");
    }
    try
    {
        byte[] fileBytes = System.IO.File.ReadAllBytes(filePath);
        return File(fileBytes, "application/csv", "取货模板.csv");
    }
    catch (Exception ex)
    {
        return new JsonResult($"模板文件异常!" + ex.Message);
    }
}

前端接口解析文件并下载

function downloadTemplate() {const { apiURL } = useAppConfig(import.meta.env, import.meta.env.PROD);
    const response = await fetch(apiURL+'/webTaskHelper/downloadTemplate', {
        method: 'GET',
        headers: {
          "token": localStorage.getItem("token") || '',
          'Content-Type': 'application/csv', //定义以什么编码来读取这个文件
        },
      });
      const data = await response.blob()
      const blob = new Blob([data])
      const url = URL.createObjectURL(blob);
      const link = document.createElement('a');
      link.href = url;
      link.download = '取货模板.csv';
      link.click();
}

 

posted @ 2024-12-27 13:49  龙卷风吹毁停车场  阅读(61)  评论(0)    收藏  举报