日期:2014-05-18 浏览次数:20589 次
// GET: /Admin/AddArticle
public ActionResult AddArticle()
{
ViewBag.AddDate = DateTime.Now;
ViewBag.FenleiID = new SelectList(db.Fenleis, "FenleiID", "FenleiName");
return View();
}
[HttpPost]
[ValidateInput(false)]
public ActionResult AddArticle(Article newArticle, HttpPostedFileBase image)
{
ViewBag.htmltext = new MvcHtmlString("Content");
ViewBag.AddDate = DateTime.Now;
int articleid = db.SaveChanges();
if (ModelState.IsValid)
{
//这是标题图片上传方法
if (image != null)
{
string year = DateTime.Now.Year.ToString();
string month = DateTime.Now.Month.ToString("00");
string day = DateTime.Now.Day.ToString("00");
string fileFolder = string.Concat("Upload/", year, "/", month, "/", day);
string path = HostingEnvironment.MapPath("~/" + fileFolder);
if (!Directory.Exists(path))
{
//在Upload目录下创建了一个文件夹
Directory.CreateDirectory(path);
}
string imagename = image.FileName;
string fileType = Path.GetExtension(image.FileName).ToLower();
if (fileType == ".jpeg" || fileType == ".jpg" || fileType == ".png" || fileType == ".gif")
{
Random ran = new Random();
string name = DateTime.Now.ToString("yyyyMMdhhmmss") + ran.Next(9999) + fileType;
image.SaveAs(Path.Combine(path, name));
string imageurl = string.Concat(HostingEnvironment.ApplicationVirtualPath, fileFolder, "/", name);
newArticle.ImageUrl = imageurl;
}
}
//这是文件上传方法
foreach(string upload in Request.Files)
{
if (Request.Files[upload].ContentLength<=0) continue;
string year = DateTime.Now.Year.ToString();
string month = DateTime.Now.Month.ToString("00");
string day = DateTime.Now.Day.ToString("00");
string fileFolder = string.Concat("Upload/", year, "/", month, "/", day);
string path = HostingEnvironment.MapPath("~/" + fileFolder);
if (!Directory.Exists(path))
{
//在Upload目录下创建了一个文件夹
Directory.CreateDirectory(path);
}
string filename = Request.Files[upload].FileName;
string fileType = Path.GetExtension(Request.Files[upload].FileName).ToLower();
string nickName = Path.GetFileName(Request.Files[upload].FileName);
Random ran = new Random();
string name = DateTime.Now.ToString("YYyyMMdhhmmss") + ran.Next(9999) + fileType;
Request.Files[upload].SaveAs(Path.Combine(path, name));
AddTempAttachment(nickName, "/" + fileFolder + "/" + name, Convert.ToInt32(Session["userid"]));
}
db.Articles.Add(newArticle);
db.SaveChanges();
//将博文的id转换为字符串
if (Request.Files != null)
{