简体   繁体   中英

Unable to upload Image to database due to Base64 error

I am following a tutorial on how to upload an image to a database and then retrieve it. My WCF service, which is working fine, has a function that inserts the data into the database like so:

public bool CreateTeam(string userId, string teamId, string name, string coach, byte[] photo)
    {
        string query = "INSERT INTO t" + userId + "(Id, Name, Coach, Photo) VALUES (@id, @name, @coach, @photo)";

        try
        {
            SqlConnection connection = new SqlConnection(ConfigurationManager.ConnectionStrings["TeamsConnectionString"].ConnectionString);
            SqlCommand command = new SqlCommand(query, connection);

            connection.Open();
            command.Parameters.AddWithValue("@id", teamId);
            command.Parameters.AddWithValue("@name", name);
            command.Parameters.AddWithValue("@coach", coach);
            command.Parameters.AddWithValue("@photo", photo);
            command.ExecuteNonQuery();
            connection.Close();

            return true;
        }

        catch (Exception ex)
        {
            Console.WriteLine("" + ex.Message);

            return false;
        }
    }

In my controller, I have a reference to the WCF Service and a HttpPostedFileBase to get the uploaded file like so:

[HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult Create(Team team)
    {
        if (ModelState.IsValid)
        {
            HttpPostedFileBase photo = Request.Files["Photo"];

            TeamsService.ServiceClient client = new TeamsService.ServiceClient();
            client.Open();

            if (client.CreateTeam(Session["DynamixSessionId"].ToString(), team.Id, team.Name, team.Coach, ConvertToBytes(photo)))
            {
                client.Close();

                return RedirectToAction("Index", "Teams");
            }

            else
            {
                return View();
            }
        }

        return View();
    }

The ConvertToBytes function is outlined below:

public byte[] ConvertToBytes(HttpPostedFileBase file)
    {
        byte[] fileBytes = null;

        BinaryReader reader = new BinaryReader(file.InputStream);
        fileBytes = reader.ReadBytes((int)file.ContentLength);

        return fileBytes;
    }

My Team model is as so:

[Key]
    [Required(AllowEmptyStrings = false, ErrorMessage = "This cannot be empty")]
    public string Id { get; set; }

    [Required(AllowEmptyStrings = false, ErrorMessage = "This cannot be empty")]
    public string Name { get; set; }

    [Required(AllowEmptyStrings = false, ErrorMessage = "This cannot be empty")]
    public string Coach { get; set; }

    public byte[] Photo { get; set; }

    public HttpPostedFileBase File { get; set; }

In my View, I have a form with the enctype attribute like so:

@using (Html.BeginForm("Create", "Teams", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
    @Html.AntiForgeryToken() 
        <div class="form-horizontal">
                @Html.ValidationSummary(true, "", new { @class = "text-danger" })
                <div class="form-group">
                    @Html.LabelFor(model => model.Id, htmlAttributes: new { @class = "control-label col-md-2" })
                    <div class="col-md-10">
                        @Html.EditorFor(model => model.Id, new { htmlAttributes = new { @class = "form-control" } })
                        @Html.ValidationMessageFor(model => model.Id, "", new { @class = "text-danger" })
                    </div>
                </div>

                <div class="form-group">
                    @Html.LabelFor(model => model.Name, htmlAttributes: new { @class = "control-label col-md-2" })
                    <div class="col-md-10">
                        @Html.EditorFor(model => model.Name, new { htmlAttributes = new { @class = "form-control" } })
                        @Html.ValidationMessageFor(model => model.Name, "", new { @class = "text-danger" })
                    </div>
                </div>

                <div class="form-group">
                    @Html.LabelFor(model => model.Coach, htmlAttributes: new { @class = "control-label col-md-2" })
                    <div class="col-md-10">
                        @Html.EditorFor(model => model.Coach, new { htmlAttributes = new { @class = "form-control" } })
                        @Html.ValidationMessageFor(model => model.Coach, "", new { @class = "text-danger" })
                    </div>
                </div>

                <div class="form-group">
                    <input type="file" name="Photo" id="Photo" />
                </div>
            </div>
}

When I click on the submit button, the other fields insert correctly and I can see them from my SQL Server database. As soon as I add my Photo field (of type varbinary ), I get the following error:

The input is not a valid Base-64 string as it contains a non-base 64 character, more than two padding characters, or an illegal character among the padding characters.

Why am I getting this error? Any suggestions on how to resolve the error?

My suggestion is that you should specify parameter type. commandd.Parameters.Add("@photo", SqlDbType.VarBinary, LengthOfFieldOnTheServerSide).Value = photo; This suggestion is based on my previous "fights" with SQL queries. For me it was creating query with system.byte [] in the place of parameter instead of actual value of byte [] .

sorry for typos I'm using StackExchange app on my phone

Why is your file upload control using the ID of your Photo field in your model? The Photo field must be of type HttpPostedFileBase in order for the image to be uploaded correctly and to avoid the Base64 error. I suggest you make the following changes:

  1. In your , add the following: ,添加以下内容:

     public HttpPostedFileBase UploadedPhoto { get; set; } 
  2. In your , add the following: ,添加以下内容:

     <input type="file" name="UploadedPhoto" id="UploadedPhoto" /> 
  3. In your , add the following: ,添加以下内容:

     HttpPostedFileBase photo = Request.Files["UploadedPhoto"]; TeamsService.ServiceClient client = new TeamsService.ServiceClient(); client.Open(); if (client.CreateTeam(Session["DynamixSessionId"].ToString(), team.Id, team.Name, team.Coach, ConvertToBytes(photo))) { client.Close(); return RedirectToAction("Index", "Teams"); } else { return View(); } 

That should solve your problem.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM