简体   繁体   English

由于Base64错误,无法将图像上传到数据库

[英]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: 我的WCF服务运行正常,它具有将数据插入数据库的功能,如下所示:

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: 在我的控制器中,我有一个对WCF服务的引用和一个HttpPostedFileBase来获取上传的文件,如下所示:

[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: 下面概述了ConvertToBytes函数:

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: 我的Team模型是这样的:

[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: 在我的视图中,我有一个带有enctype属性的表单,如下所示:

@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. 当我单击提交按钮时,其他字段将正确插入,并且可以从我的SQL Server数据库中看到它们。 As soon as I add my Photo field (of type varbinary ), I get the following error: 一旦添加我的Photo域(类型为varbinary ),就会出现以下错误:

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. 输入内容不是有效的Base-64字符串,因为它包含非Base 64字符,两个以上的填充字符或填充字符中的非法字符。

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. 这个建议是基于我之前对SQL查询的“打架”。 For me it was creating query with system.byte [] in the place of parameter instead of actual value of byte [] . 对我来说,它正在使用system.byte []代替参数byte []的实际值来创建查询。

sorry for typos I'm using StackExchange app on my phone 抱歉打错我在手机上使用StackExchange应用程序

Why is your file upload control using the ID of your Photo field in your model? 为什么您的文件上传控件使用模型中“ Photo字段的ID? The Photo field must be of type HttpPostedFileBase in order for the image to be uploaded correctly and to avoid the Base64 error. Photo字段必须为HttpPostedFileBase类型,以便正确上传图像并避免Base64错误。 I suggest you make the following changes: 我建议您进行以下更改:

  1. In your model , add the following: 模型中 ,添加以下内容:

     public HttpPostedFileBase UploadedPhoto { get; set; } 
  2. In your view , add the following: 在您的视图中 ,添加以下内容:

     <input type="file" name="UploadedPhoto" id="UploadedPhoto" /> 
  3. In your controller , 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. 那应该解决您的问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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