.net 根据路径将本地文件转为流返回前端下载

.net Core中根据文件路径和名字将文件转为流返回给前端提供下载,需要传入文件路径(不带域名),和文件名称(用于下载使用),前端使用<a></a>标签来进行访问下载,或者 location.href 来访问
 [ApiController]
    [Route("[controller]")]
    public class FilesController : ControllerBase
    {
        private readonly IWebHostEnvironment _webHostEnvironment;
        
        public FilesController(IWebHostEnvironment webHostEnvironment)
        {
            _webHostEnvironment = webHostEnvironment;
        }

       /// <summary>
       /// 获取文件流
       /// </summary>
       /// <param name="url">文件路径</param>
       /// <param name="name">文件名称</param>
       /// <returns></returns>
        [HttpGet]
        public async Task<IActionResult> UploadFile(string url,string name)
        {
            string webRootPath = _webHostEnvironment.WebRootPath;
            string contentRootPath = _webHostEnvironment.ContentRootPath;
            var str = url.Split('.');//获取文件后缀
            var newpath = contentRootPath + "/wwwroot/" + url;//我这里的url是/files/202205/xxx.txt;不带域名,因为是netcore项目所以前面加上wwwroot
            FileStream fs = new FileStream(newpath, FileMode.OpenOrCreate, FileAccess.Read);
            byte[] vs = new byte[fs.Length];
            while (true)
            {
                int r = fs.Read(vs, 0, vs.Length);
                string s = Encoding.UTF8.GetString(vs, 0, r);
                if (r == 0)
                {
                    fs.Close();
                    break;
                }
            }

            return File(vs, "application/"+ str[1].ToString(), name+"."+ str[1].ToString());
        }
    }

contentRoot是使用程序更目录

ContentRoot: C:\MyApp\wwwroot

WebRoot: C:\MyApp\wwwroot\wwwroot


这里建议使用contentRoot在后面加上/wwwroot/

读到文件之后将它放入byte数组里面写入流,防止有较大文件所以上面使用while循环写入

 

 

posted @ 2022-05-23 10:15  吃兔子的萝卜7  阅读(1137)  评论(0编辑  收藏  举报