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

斯文·隆伦德(Sven Ronnlund)

我正在遵循有关如何将图像上载到数据库然后进行检索的教程。我的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字符,两个以上的填充字符或填充字符中的非法字符。

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

剃刀

为什么您的文件上传控件使用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();
    }
    

那应该解决您的问题。

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

无法将图像上传到数据库

Swift 2,将base64图像上传到PHP

通过AWS Ruby SDK将Base64图像数据上传到S3

尝试使用按钮将图像上传到我在 CodeIgniter 中的数据库,但出现错误

使用php将图像上传到sql数据库时显示错误

无法将较大(大小)的图像从android应用程序上传到数据库

将图像上传到Firebase存储和数据库

将图像上传到mariadb数据库

将多个图像上传到MySql数据库

将图像上传到数据库,但出现异常

CodeIgniter:将图像上传到路径和数据库

如何将图像从ViewModel上传到数据库

将多个图像上传到SQL数据库-

将多个图像上传到数据库MYSQLI

在Cordova中获取Base64 ImageData,将其上传到mysql数据库中并在Cordova中显示

PHP Mysqli:无法将文件上传到数据库

图像上传到数据库

能够将图像上传到Dropbox,但无法在数据库上获取和存储图像URL

Swift-将base64编码的图像上传到php并显示图像

转换为base64后如何将画布图像插入数据库

流星:上传图像并将其作为base64字符串保存到数据库

无法将图像上传到数据库和应用程序(fileuploader js文件)?fileuploader js

使用Java将Base64编码的图像上传到Amazon s3

如何将这个基于base64转换图像的gridview上传到firebase?

通过Node.js将base64编码的图像上传到Amazon S3

将Base64编码的图像上传到PHP服务器

通过Node将base64图像从react-webcam上传到cloudinary

将图像编码为base64并上传到Phonegap中的Web服务

将 Base64 编码图像上传到 php 服务器