繁体   English   中英

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

[英]Unable to upload Image to database due to Base64 error

我正在关注有关如何将图像上传到数据库然后进行检索的教程。 我的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;
        }
    }

在我的控制器中,我有一个对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();
    }

下面概述了ConvertToBytes函数:

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

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

        return fileBytes;
    }

我的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; }

在我的视图中,我有一个带有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>
}

当我单击提交按钮时,其他字段将正确插入,并且可以从我的SQL Server数据库中看到它们。 一旦添加我的Photo域(类型为varbinary ),就会出现以下错误:

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

为什么会出现此错误? 关于如何解决错误的任何建议?

我的建议是您应该指定参数类型。 commandd.Parameters.Add("@photo", SqlDbType.VarBinary, LengthOfFieldOnTheServerSide).Value = photo; 这个建议是基于我之前对SQL查询的“打架”。 对我来说,它正在使用system.byte []代替参数byte []的实际值来创建查询。

抱歉打错我在手机上使用StackExchange应用程序

为什么您的文件上传控件使用模型中“ Photo字段的ID? Photo字段必须为HttpPostedFileBase类型,以便正确上传图像并避免Base64错误。 我建议您进行以下更改:

  1. 模型中 ,添加以下内容:

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

     <input type="file" name="UploadedPhoto" id="UploadedPhoto" /> 
  3. 在您的控制器中 ,添加以下内容:

     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(); } 

那应该解决您的问题。

暂无
暂无

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

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