诗情寻知己
揽几缕、轻挽起,暮暮朝朝与君语。
public class DownloadController : BaseController
{
        private readonly IHostingEnvironment _hostingEnvironment;

        public DownloadController(IHostingEnvironment hostingEnvironment,IHttpContextAccessor httpContext)
        {
            _httpContext = httpContext;
            _hostingEnvironment = hostingEnvironment;
        }
   
        [HttpGet]
        public IActionResult DownloadFile()
        {
            try
            {
                string contentRootPath = _hostingEnvironment.ContentRootPath;
                string filePath = Path.Combine(contentRootPath, "Template", "test.xlsx");
                FileStream fileStream = new FileStream(filePath, FileMode.Open);
                return File(fileStream, "application/octet-stream", "test-1.xlsx");
            }
            catch (Exception ex)
            {
                return new JsonResult(new AjaxResult<string> { Code = ResultCodeEnum.ERROR, Message = $"Failed to download file : {ex.Message}", Data = $"" });
            }
        }
}

js 调用直接使用以下代码

<script type="text/javascript">
    window.onload = function () {
        window.location.href = "/Download/DownloadFile"; 
};

</script>

 

posted on 2023-02-09 16:58  诗情寻知己  阅读(73)  评论(0编辑  收藏  举报