后端接口返回文件
[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(); }
标签:webapi,core,asp,const,文件,link,blob,csv,模板 From: https://www.cnblogs.com/tlfe/p/18635562