ASP MVC图像上传错误“输入不是有效的Base-64字符串”

问题描述 投票:2回答:2

我有此表单,正在尝试上传图像。当我单击提交按钮时,出现以下错误:

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

控制器从未到达,因为在我上传图像后就会发生错误。我不知所措。任何帮助表示赞赏!

@using (Html.BeginForm("Create", "Create", FormMethod.Post, new { enctype = "multipart/form-data"})) 
{
    @Html.AntiForgeryToken()

    <div class="form-group">
        <div class="col-md-10">
            @Html.LabelFor(model => model.ComponentModel.Image, htmlAttributes: new {@class = "control-label col-md-2"})
            <a class="btn" href="javascript:;">
                Choose File...
                <input type="file" name="Image" Size="40" style="position: absolute; z-index: 2; top: 0; left: 0; filter: alpha(opacity=0); opacity: 0; background-color: transparent; color: transparent"
                       onchange='$("#upload-file-info").html($(this).val());'/>
            </a>
            <span class="label label-info" id="upload-file-info"></span>
        </div>
    </div>

    <div class="form-group">
        <div class="col-md-offset-2 col-md-10">
            <input type="submit" value="Create" class="btn btn-default"/>
        </div>
    </div>
}

更新:

这是创建控制器:

    [AcceptVerbs(HttpVerbs.Post)]
    public ActionResult Create(Component component, HttpPostedFileBase image = null)
    {
        if (ModelState.IsValid)
        {
            if (image != null)
            {
                component.Image = new byte[image.ContentLength];
                image.InputStream.Read(component.Image, 0, image.ContentLength);
            }
            componentRepository.InsertComponent(component);
            componentRepository.Save();
            return RedirectToAction("Index", "Home");
        }
        return RedirectToAction("Index", component);
    }
asp.net-mvc base64 image-upload
2个回答
4
投票

您在这里确实没有提供足够的信息,但是根据错误消息,我将做出一个疯狂的猜测。

您说它没有命中您的控制器,但必须是要命中您的控制器。该错误来自ASP.NET,因此将返回到服务器。

您已将输入的文件绑定到Image,我的猜测是Image是模型上的字节数组。您不能直接发布到字节数组。您需要绑定到HttpPostedFileBase类型的属性,然后可以从中读取字节数组并将其设置为其他属性。


0
投票

public HttpPostedFileBase image { get; set; }在您的模型上使用<input type="file" name="image" />在您的View名称道具上使用它应与HttpPostedFileBase图像相同,并在post方法上捕获它并将其转换为字节后]

© www.soinside.com 2019 - 2024. All rights reserved.