File Upload ASP.NET MVC 3.0

后端 未结 21 1225
无人共我
无人共我 2020-11-22 01:09

(Preface: this question is about ASP.NET MVC 3.0 which was released in 2011, it is not about ASP.NET Core 3.0 which was released in 2019)

I want to

21条回答
  •  野的像风
    2020-11-22 01:48

    Here is my working example:

    [HttpPost]
        [ValidateAntiForgeryToken]
        public async Task Create(Product product, HttpPostedFileBase file)
        {
            if (!ModelState.IsValid)
                return PartialView("Create", product);
            if (file != null)
            {
    
                var fileName = Path.GetFileName(file.FileName);
                var guid = Guid.NewGuid().ToString();
                var path = Path.Combine(Server.MapPath("~/Content/Uploads/ProductImages"), guid + fileName);
                file.SaveAs(path);
                string fl = path.Substring(path.LastIndexOf("\\"));
                string[] split = fl.Split('\\');
                string newpath = split[1];
                string imagepath = "Content/Uploads/ProductImages/" + newpath;
                using (MemoryStream ms = new MemoryStream())
                {
                    file.InputStream.CopyTo(ms);
                    byte[] array = ms.GetBuffer();
                }
                var nId = Guid.NewGuid().ToString();
                // Save record to database
                product.Id = nId;
                product.State = 1;
                product.ImagePath = imagepath;
                product.CreatedAt = DateTime.Now;
                db.Products.Add(product);
                await db.SaveChangesAsync();
                TempData["message"] = "ProductCreated";
    
                //return RedirectToAction("Index", product);
            }
            // after successfully uploading redirect the user
            return Json(new { success = true });
        }
    

提交回复
热议问题