示例#1
0
        public JsonResult AddNews(AddNews news, IFormCollection collection)
        {
            if (news.NewsClassifyId <= 0 || string.IsNullOrEmpty(news.Title) || string.IsNullOrEmpty(news.Contents))
            {
                return(Json(new ResponseModel {
                    code = 0, message = "参数有误"
                }));
            }
            var files = collection.Files;

            if (files.Count > 0)
            {
                string   webRootPath     = host.WebRootPath;
                string   relativeDirPath = "\\NewsPic";
                string   absolutePath    = webRootPath + relativeDirPath;
                string[] fileTypes       = new string[] { ".gif", ".jpg", ".jpeg", ".png", ".bmp" };//定义允许上传的图片格式
                string   extension       = Path.GetExtension(files[0].FileName);
                if (fileTypes.Contains(extension))
                {
                    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))
                    {
                        files[0].CopyTo(stream);
                    }
                    news.Image = "/NewsPic/" + fileName;
                    return(Json(newsServices.AddNews(news)));
                }
                return(Json(new ResponseModel {
                    code = 0, message = "图片格式有误"
                }));
            }
            return(Json(new ResponseModel {
                code = 0, message = "请上传图片文件"
            }));
        }