1. Asp.Net Core Mvc方式
public class UploadController : Controller { private IHostingEnvironment _hostingEnv; public UploadController(IHostingEnvironment hostingEnv) { _hostingEnv = hostingEnv; } [HttpPost] public IActionResult Index() { var file = Request.Form.Files; if (file.Sum(f => f.Length) > 0) { foreach (var pic in file) { var picname = ContentDispositionHeaderValue .Parse(pic.ContentDisposition) .FileName .Trim('"'); var exname = picname.Substring(picname.LastIndexOf(".")); var picfullname = DateTime.Now.ToString() + exname; picname = _hostingEnv.WebRootPath + $@"UploadImg{picfullname}"; using (FileStream fs = System.IO.File.Create(picname)) { pic.CopyTo(fs); fs.Flush(); } } } return Content("ok"); } }
2.Asp.Net Mvc方式
public class UploadController : Controller { [HttpPost] public ActionResult Index(HttpPostedFileBase picture) { if (picture.ContentLength > 0) { string filePath = Path.Combine(HttpContext.Server.MapPath("../UploadImg"), Path.GetFileName(picture.FileName)); picture.SaveAs(filePath); } return Content("ok"); } }
HTML页面
<form method="post" enctype = "multipart/form-data"> <div class="form-group"> <label class="control-label col-md-2">预览图</label> <div class="col-md-4"> <div class="fileupload fileupload-new" data-provides="fileupload"> <div class="fileupload-new img-thumbnail" style=" 200px; height: 150px;"> <img src="~/Images/AAAAAA&text=no+image.png" /> </div> <div class="fileupload-preview fileupload-exists img-thumbnail" style=" 200px; max-height: 150px"></div> <div> <span class="btn btn-default btn-file"><span class="fileupload-new">选择图片</span><span class="fileupload-exists">更换</span><input type="file" name="pic" id="picture"></span><a class="btn btn-default fileupload-exists" data-dismiss="fileupload" href="#">清除</a> </div> </div> </div> </div> </form>