1. 前台 cshtml
@model BLL.BLL.Product @{ ViewBag.Title = "Add"; }Add
2. 后台Controller
public ActionResult Add() { ShoppingDataContext dc = new ShoppingDataContext(); //初始化下拉列表框的数据 var linq = from c in dc.ProductCategories select new { c.CategoryId,c.CategoryName}; ListcList = new List (); foreach(var category in linq){ SelectListItem item = new SelectListItem() { Text=category.CategoryName, Value=category.CategoryId}; cList.Add(item); } ViewBag.cList = cList; return View(); } [HttpPost] public ActionResult Add(Product p) { Stream uploadStream = null; FileStream fs = null; try { //文件上传,一次上传1M的数据,防止出现大文件无法上传 HttpPostedFileBase postFileBase = Request.Files["ProductImage"]; uploadStream = postFileBase.InputStream; int bufferLen = 1024; byte[] buffer = new byte[bufferLen]; int contentLen = 0; string fileName = Path.GetFileName(postFileBase.FileName); string baseUrl = Server.MapPath("/"); string uploadPath = baseUrl + @"Images\Upload\Product\"; fs = new FileStream(uploadPath + fileName, FileMode.Create, FileAccess.ReadWrite); while ((contentLen = uploadStream.Read(buffer, 0, bufferLen)) != 0) { fs.Write(buffer, 0, bufferLen); fs.Flush(); } //保存页面数据,上传的文件只保存路径 string productImage = "/Images/Upload/Product/" + fileName; p.ProductImage = productImage; p.ProductId = Guid.NewGuid().ToString(); p.CreationDate = DateTime.Now; ShoppingDataContext dc = new ShoppingDataContext(); dc.Products.InsertOnSubmit(p); dc.SubmitChanges(); } catch (Exception ex) { ex.StackTrace.ToString(); } finally { if(null !=fs){ fs.Close(); } if (null != uploadStream) { uploadStream.Close(); } } return RedirectToAction("../Category/ListProducts", new { cId=p.CId}); }
3. 修改web.config 中对文件上传大小的限制
在 <system.web></system.web> 直接增加如下: