码迷,mamicode.com
首页 > Web开发 > 详细

.Net Core 上传图片

时间:2020-06-28 09:15:48      阅读:72      评论:0      收藏:0      [点我收藏+]

标签:created   逻辑   contains   filetype   task   roo   sts   extension   let   

NnGet

 using Microsoft.AspNetCore.Hosting;

实现逻辑

        private IHostingEnvironment _host;
        public TestController( IHostingEnvironment host)
        { 
            this._host = host;
        }
        [HttpPost]
        public async Task<JsonResult> AddTest(Test test, IFormCollection collection)
        {
            var files = collection.Files;
            if (files.Count > 0)
            {
                var absolutePath = _host.WebRootPath+ "\\TestPic";
                 
                string[] fileType = new string[] { ".gif", ".jpg", ".jpeg", ".bmp", ".png" };
                string extension = Path.GetExtension(files[0].FileName);
                if (fileType.Contains(extension.ToLower()))
                {
                    if (!Directory.Exists(absolutePath))
                    {
                        Directory.CreateDirectory(absolutePath);
                    }
                    string fileName = DateTime.Now.ToString("yyyyMMddHHmmss") + extension;
                    var filePath = absolutePath + "\\" + fileName;
                    using (var stream = new FileStream(filePath, FileMode.Create))
                    {
                        await files[0].CopyToAsync(stream);
                    }
                    
                    return Json(new { Result = "上传成功", Flag = 1 } );
                }
                else
                {
                    return Json(new { Result = "图片格式不正确", Flag = 0 });
                }
            }
            return Json(new { Result = "请上传图片", Flag = 0 });
        }

  

.Net Core 上传图片

标签:created   逻辑   contains   filetype   task   roo   sts   extension   let   

原文地址:https://www.cnblogs.com/HYJ0201/p/13201022.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!