asp.net core 图片文件上传

csharp

浏览数:386

2019-1-7


UploadFiles.cs

        /// <summary>
        /// 文件上传
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public async Task<IActionResult> UploadFiles()
        {
            string filesPath = "";
            var files = Request.Form.Files;
            string tempPath = "uploadfiles" + '\\' + DateTime.Now.ToString("yyyyMMdd");//相对路径
            string physicPath = _env.WebRootPath + '\\' + tempPath;//物理路径
            if (!Directory.Exists(physicPath))
            {
                Directory.CreateDirectory(physicPath);
            }
            foreach (var formFile in files)
            {
                if (formFile.Length > 0)
                {
                    //文件名字
                    string filesName = DateTime.Now.ToFileTime() + Path.GetExtension(formFile.FileName);
                    //绝对路径
                    string fileFullPath = Path.Combine(physicPath, filesName);
                    using (var stream = new FileStream(fileFullPath, FileMode.Create))
                    {
                        await formFile.CopyToAsync(stream);//保存文件
                    }
                    filesPath += tempPath + '\\' + filesName + ',';
                }
            }
            filesPath = filesPath.TrimEnd(',');
            return Ok(new { filesPath });
        }