1. 在视图中要写
@using (Html.BeginForm("AddProductaction","Admin",FormMethod.Post, new { enctype = "multipart/form-data" })) { <input type="file" multiple id="pic_selector" name="ImgUrl" /> }
2. 在控制器中
//前台页面通过 < file name = "img" > 标签数组上传图片,后台根据Request.Files["img"]来接收前台上传的图片。
System.Web.HttpFileCollection files = System.Web.HttpContext.Current.Request.Files;
if (files.Count == 0)
return View();
for (int i = 0; i < files.AllKeys.Count(); i++)
{
if (files.AllKeys[i] != "img")
{
if (files[i].FileName.Length > 0)
{
System.Web.HttpPostedFile postedfile = files[i];
string filePath = "";
var ext = Path.GetExtension(postedfile.FileName);
var fileName = DateTime.Now.Ticks.ToString() + ext;
// 组合文件存储的相对路径
filePath = "/UploadImg/" + fileName;
// 将相对路径转换成物理路径
var path = Server.MapPath(filePath);
postedfile.SaveAs(path);
string fex = Path.GetExtension(postedfile.FileName);
//存储产品轮播图信息
}
}
}
3. 上传单个图片
private string SaveImg(HttpPostedFileBase file, string fileName, int userID) { //图片路径:Upload+当前日期+当前userID string filePath = "/Upload/"+DateTime.Now.ToString("yyyy-MM-dd")+"/"+userID.ToString()+"/"; if (!Directory.Exists(Server.MapPath(filePath))) { Directory.CreateDirectory(Server.MapPath(filePath)); } string returnPath = filePath + DateTime.Now.ToString("yyyyMMddhhmmssffff") + fileName; string absoluteFilePath = Server.MapPath(filePath) + DateTime.Now.ToString("yyyyMMddhhmmssffff") + fileName; file.SaveAs(absoluteFilePath); return returnPath; }