.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);php

在.Net Core 中沒有SaveAsweb

相關文章
相關標籤/搜索