C# 上传文件至指定目录,并返回文件路径

 

/// <summary>
        /// 上传图片并返回文件路径
        /// </summary>
        /// <param name="file"></param>
        /// <returns></returns>
        [HttpPost("UploadImage")]        
        public async Task<IActionResult> UploadImage(IFormFile file)
        {
            if (file == null || file.Length == 0)
                return BadRequest("未检测到图片信息!");

            string fileName = Guid.NewGuid().ToString() + Path.GetExtension(file.FileName);
            //上传路径
            //string folderName = "UpImg" + "\\";
            string folderName = "UpImg";
            string folderPath = Path.Combine(_webHostEnvironment.ContentRootPath, folderName);
            //检测上传路径是否存在,不存在创建
            if (!Directory.Exists(folderPath))
            {
                Directory.CreateDirectory(folderPath);
            }
            string filePath = Path.Combine(folderPath, fileName);

            using (var stream = new FileStream(filePath, FileMode.Create))
            {
                await file.CopyToAsync(stream);
            }
            

            //var filePath = Path.Combine(Directory.GetCurrentDirectory(), fileName);

            return Ok(filePath);
        }

 

posted @ 2023-07-04 11:05  一介桃白白  阅读(389)  评论(0编辑  收藏  举报