.Net Core 上传图片

        /// <summary>
        /// 图片上传并存入数据库
        /// </summary>
        /// <returns></returns>
        public JsonResult InsertPicture()
        {
            var uploadfile = Request.Form.Files[0];
            var now = DateTime.Now;
            var webRootPath = _environment.WebRootPath;
            var filePath = string.Format("/Uploads/Images/{0}/{1}/{2}/", now.ToString("yyyy"), now.ToString("yyyyMM"), now.ToString("yyyyMMdd"));

            if (!Directory.Exists(webRootPath + filePath))
            {
                Directory.CreateDirectory(webRootPath + filePath);
            }

            if (uploadfile != null)
            {
                //文件后缀
                var fileExtension = Path.GetExtension(uploadfile.FileName);

                //判断后缀是否是图片
                const string fileFilt = ".gif|.jpg|.php|.jsp|.jpeg|.png|......";
                if (fileExtension == null)
                {
                    return new JsonResult(new JsonResultModel { isSucceed = false, resultMsg = "上传的文件没有后缀" });
                }
                if (fileFilt.IndexOf(fileExtension.ToLower(), StringComparison.Ordinal) <= -1)
                {
                    return new JsonResult(new JsonResultModel { isSucceed = false, resultMsg = "上传的文件不是图片" });
                }

                //判断文件大小    
                long length = uploadfile.Length;
                if (length > 1024*1024*2) //2M
                {
                    return new JsonResult(new JsonResultModel { isSucceed = false, resultMsg = "上传的文件不能大于2M" });
                }

                var strDateTime = DateTime.Now.ToString("yyMMddhhmmssfff"); //取得时间字符串
                var strRan = Convert.ToString(new Random().Next(100, 999)); //生成三位随机数
                var saveName = strDateTime + strRan + fileExtension;

                //插入图片数据
                var picture = new Picture
                {
                    MimeType = uploadfile.ContentType,
                    AltAttribute = "",
                    FilePath = filePath + saveName,
                    CreatedDateTime = DateTime.Now
                };
                using (FileStream fs = System.IO.File.Create(webRootPath + filePath + saveName))
                {
                    uploadfile.CopyTo(fs);
                    fs.Flush();
                }
                _pictureService.Insert(picture);
                return new JsonResult(new  {isSuccess = true, returnMsg = "上传成功", imgId = picture.Id, imgUrl = picture.FilePath});
            }
            return new JsonResult(new JsonResultModel { isSucceed = false, resultMsg = "上传失败" });
        }

最重要的一行代码就是 uploadfile.CopyTo(fs);

在.Net Core 中没有SaveAs

 

posted @ 2017-01-13 16:35  上古时期的码农  阅读(4512)  评论(4编辑  收藏  举报