.Net上传图片

效果图:

.Net上传图片_第1张图片
.Net上传图片_第2张图片

代码如下:
引用:js,css



附件下载请点击这里

View里的代码:

@using (Html.BeginForm("Create", "RotatePic", FormMethod.Post, new { id = "formid", enctype = "multipart/form-data" })) { @Html.AntiForgeryToken()
![](http://www.placehold.it/200x150/EFEFEF/AAAAAA&text=no+image)
Select image Change Remove
}
@section scripts{ }

Controller里的代码:

        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Create(RotatePic rotatePic, HttpPostedFileBase file)
        {
            if (ModelState.IsValid)
            {
                //轮播图
                if (file != null && file.FileName != "")
                {
                    if (System.IO.Path.GetExtension(file.FileName).ToLower() == ".jpg" || System.IO.Path.GetExtension(file.FileName).ToLower() == ".png")
                    {
                        rotatePic.BannerPic = Updatefile(file);
                    }
                    else
                    {
                        ViewBag.msg = "";
                        return View();
                    }
                }

                if (rotatePic != null)
                {
                    rotatePic.CreateTime = DateTime.Now;
                    db.RotatePic.Add(rotatePic);
                    db.SaveChanges();
                }
                return RedirectToAction("Index");
            }
            return View();
        }
//图片处理,直接复制代码
 public string Updatefile(HttpPostedFileBase file)
        {
            string path = "";
            if (file != null)
            {
                var fileName = Path.Combine(Request.MapPath("~/Upload"), Path.GetFileName(file.FileName));
                string ext = System.IO.Path.GetExtension(file.FileName);
                if (!Directory.Exists(fileName))
                {
                    string n = Guid.NewGuid().ToString();
                    string newname = n + ext;
                    fileName = Path.Combine(Request.MapPath("~/Upload"), Path.GetFileName(newname));

                    if (ext.ToLower() == ".jpg")
                    {
                        Common.ImageHelper.CompressionJpgImage(file.InputStream, fileName);
                    }
                    else
                    {
                        Common.ImageHelper.CompressionPngImage(file.InputStream, fileName);
                    }
                    path = "../Upload/" + Path.GetFileName(newname);
                }
                else
                {
                    if (ext.ToLower() == ".jpg")
                    {
                        Common.ImageHelper.CompressionJpgImage(file.InputStream, fileName);
                    }
                    else
                    {
                        Common.ImageHelper.CompressionPngImage(file.InputStream, fileName);
                    }
                    path = "../Upload/" + Path.GetFileName(file.FileName);
                }
            }
            return path;
        }

你可能感兴趣的:(.Net上传图片)