ABP VNext API层文件上传下载

ABP VNext API层文件上传下载

  • 1.上传
  • 2.下载

1.上传

        /// 
        /// 上传单个文件
        /// 
        /// 文件
        /// 
        [HttpPost("upload")]
        public async Task<string> Upload(IFormFile file)
        {
            if (file is null)
            {
                throw new UserFriendlyException("请选择上传的文件");
            }

            //获取当前web目录
            var webRootPath = $"{AppDomain.CurrentDomain.BaseDirectory}/wwwroot/Upload/";
            if (!Directory.Exists(webRootPath))
            {
                Directory.CreateDirectory(webRootPath);
            }

            //文件后缀
            var fileExtension = Path.GetExtension(file.FileName)?.ToLower();
            if (string.IsNullOrEmpty(fileExtension))
            {
                throw new UserFriendlyException("文件无法识别!");
            }

            //判断后缀是否是文件
            var fileFilt = new List<string> { ".pdf", ".doc", ".docx", ".xls", ".xlsx", ".mp4" };
            if (!fileFilt.Any(p => p.Equals(fileExtension)))
            {
                throw new UserFriendlyException("请上传pdf、Work、Excel格式的文件");
            }

            var strDateTime = DateTime.Now.ToString("yyMMddhhmmssfff"); //取得时间字符串
            var saveName = strDateTime + fileExtension;

            //插入文件数据
            using (FileStream fs = System.IO.File.Create(webRootPath + saveName))
            {
                await file.CopyToAsync(fs);
                fs.Flush();
            }

            saveName = "/wwwroot/Upload/" + saveName;
            return saveName;
        }

2.下载


        /// 
        /// 下载文件
        /// 
        /// 
        [HttpPost("down")]
        public async Task<ActionResult> Down(string path)
        {
            var stream = System.IO.File.OpenRead(path);
            string fileExt = Path.GetExtension(path);
            //获取文件的ContentType
            var provider = new FileExtensionContentTypeProvider();
            var memi = provider.Mappings[fileExt];
            return File(stream, memi, Path.GetFileName(path));
        }

你可能感兴趣的:(ABP,vNext,前端,javascript,开发语言)