Save image to database with ASP.NET MVC

后端 未结 2 1359
谎友^
谎友^ 2021-01-03 02:48

I am trying to save image to database with Create method. but when try this code, I get this error:

The input is not a valid Base-64 string as it cont

相关标签:
2条回答
  • 2021-01-03 03:26

    Try this:

    string savedFileName = Server.MapPath("/Resources/images/customers/" + "customers_" + saveCustomer.FirstName + "_" + saveCustomer.LastName + ".jpg");
    

    instead of

    string savedFileName = Path.Combine(
                          ConfigurationManager.AppSettings["FileUploadDirectory"],
                          "customers_" + saveCustomer.FirstName + "_" + saveCustomer.LastName + ".jpg");
    
    1. If your Customer Models contains the Image field, it's not necessary to save to server-side Dirs.

    2. the form post should not have the upload file field, please change the Controller to:

    ================================

    [Authorize]
    [HttpPost]
    public ActionResult Create([Bind(Exclude = "ImageData")]Customers saveCustomer, HttpPostedFileBase ImageData)
    {
        try
        {
            // TODO: Add insert logic here
            var upload = Request.Files["ImageData"];
            string savedFileName = "";  //string for saving the image server-side path          
            if (upload.ContentLength > 0)
            {
                 savedFileName = Server.MapPath("/Resources/images/customers/" + "customer_" + saveCustomer.FirstName + "_" + saveCustomer.LastName + ".jpg"); //get the server-side path for store image 
                upload.SaveAs(savedFileName); //*save the image to server-side 
            }
            var index = savedFileName.IndexOf(@"\Resources\");            
            saveCustomer.ImageData = savedFileName.Substring(index, savedFileName.Length - index); //set the string of image server-side path to add-object             
            _db.Customers.InsertOnSubmit(saveCustomer); // save all field to databae (includes image server-side path)
            _db.SubmitChanges();  // save database changes
            return RedirectToAction("Index");
        }
        catch
        {
            return View();
        }
    } 
    
    0 讨论(0)
  • 2021-01-03 03:28
    private byte[] ImageToBytes(Image img, ImageFormat format)
    {            
     MemoryStream mstream = new MemoryStream();
     img.Save(mstream, format);
     mstream.Flush();
     return mstream.ToArray();
    }
    
    0 讨论(0)
提交回复
热议问题