5

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 contains a non-base 64 character, more than two padding characters, or a non-white space character among the padding characters.*

I am very beginner to MVC. I will really appreciate for the response, Many thanks in advance.

[Authorize]
[HttpPost]
public ActionResult Create(Customers saveCustomer)
{
    try
    {
        // TODO: Add insert logic here
        var upload = Request.Files["ImageData"];
        if (upload.ContentLength > 0)
        {
            string savedFileName = Path.Combine(
                  ConfigurationManager.AppSettings["FileUploadDirectory"],
                  "customers_" + saveCustomer.FirstName + "_" + saveCustomer.LastName + ".jpg");
            upload.SaveAs(savedFileName);
        }
        _db.Customers.InsertOnSubmit(saveCustomer);
        _db.SubmitChanges();
        return RedirectToAction("Index");
    }
    catch
    {
        return View();
    }
}

Here is my create view code:

<%@ Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage<Reservation.Models.Customers>" %>    
<asp:Content ID="Content1" ContentPlaceHolderID="TitleContent" runat="server">
    Create
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">
    <h2>
        Create</h2>
    <% using (Html.BeginForm("Create", "Customers", FormMethod.Post, new {enctype="multipart/form-data"})) {%>
    <%: Html.ValidationSummary(true) %>
    <fieldset>
        <legend>Add new customer record</legend>
        <div class="editor-label">
            <%: Html.LabelFor(model => model.FirstName) %>
        </div>
        <div class="editor-field">
            <%: Html.TextBoxFor(model => model.FirstName) %>
            <%: Html.ValidationMessageFor(model => model.FirstName) %>
        </div>
        <div class="editor-label">
            <%: Html.LabelFor(model => model.LastName) %>
        </div>
        <div class="editor-field">
            <%: Html.TextBoxFor(model => model.LastName) %>
            <%: Html.ValidationMessageFor(model => model.LastName) %>
        </div>
        <div class="editor-label">
            <%: Html.LabelFor(model => model.Email) %>
        </div>
        <div class="editor-field">
            <%: Html.TextBoxFor(model => model.Email) %>
            <%: Html.ValidationMessageFor(model => model.Email) %>
        </div>
        <div class="editor-label">
            <%: Html.LabelFor(model => model.Phone) %>
        </div>
        <div class="editor-field">
            <%: Html.TextBoxFor(model => model.Phone) %>
            <%: Html.ValidationMessageFor(model => model.Phone) %>
        </div>
        <div class="editor-label">
            <%: Html.LabelFor(model => model.CustomerNote) %>
        </div>
        <div class="editor-field">
            <%: Html.TextBoxFor(model => model.CustomerNote) %>
            <%: Html.ValidationMessageFor(model => model.CustomerNote) %>
        </div>

        <div>
           <input type="file" id="ImageData" name="ImageData" />

        </div>

        <p>
            <input type="submit" value="Add recrod" />
        </p>
    </fieldset>
    <% } %>
    <div>
        <%: Html.ActionLink("Back to List", "Index") %>
    </div>
</asp:Content>

Web.config:

<appSettings>
    <add key="FileUploadDirectory" value="~/Resources/images/customers/" />
</appSettings>

Database entry:

Column Name  Data Type  Allow Nulls
ImageData    image      yes 
4
  • You have to convert it before saving it anywhere. Commented Apr 21, 2011 at 12:02
  • Thanks for your reponse, could you please explain, where I can add this code. can you please add the following code into my example. so that I can cleary get clear idea. Commented Apr 21, 2011 at 12:16
  • Could you post the data where the Image is written into the Request? Commented Apr 21, 2011 at 12:29
  • I think this line does it _db.Customers.InsertOnSubmit(saveCustomer); i have posted all code above, there is nothing else in my code, maybe I might be missing that? Commented Apr 21, 2011 at 12:36

2 Answers 2

1

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();
    }
} 
Sign up to request clarification or add additional context in comments.

26 Comments

changed it to your's code, but still getting the same error :-(
Since it's nearly the same and you just changed the path... (?)
yes that's what I did, changed that one line of code, but no luck, could you please check all my code file, am I doing tha right way?
Could you give the the Customer "Model", it's contains a Image filed?
I am doing this with Linq, I have not created any model for it, I draged the customer table onto my Reservation.dbml file, which is doing this all. I was able to store all the other information, but after adding the image file, I got that error.
|
0
private byte[] ImageToBytes(Image img, ImageFormat format)
{            
 MemoryStream mstream = new MemoryStream();
 img.Save(mstream, format);
 mstream.Flush();
 return mstream.ToArray();
}

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.