使用 Kendo Ui 上传将图像发送到数据库

Send image to database using Kendo Ui Upload

在我的 MVC 项目中,我有一个表单,让用户可以使用 Kendo Ui 上传来上传图像。 这是我的看法:

@using Kendo.Mvc.UI
@model DevelopmentNotesProject.Models.NoteForm


@{
    ViewBag.Title = "Index";
}

<script>
    $(function () {
        $("form").kendoValidator();
    });

    function limitUpload()
    {
        if ($("span.k-filename").html() != "" || $("span.k-filename").html() != "undefined") {
            $("div.k-dropzone div.k-button.k-upload-button input").attr('disabled', 'disabled');
        }
    }

    function enableUploadafterRemove()
    {
        $("div.k-dropzone div.k-button.k-upload-button input").removeAttr('disabled');
    }

    function onSuccess(e) {
        limitUpload();
    }

    function onRemove(e) {
        alert("innn");
        enableUploadafterRemove();
    }


    $(document).ready(function () {


    });
</script>

<style>
    form,h2 {margin:0 auto;max-width:900px}
</style>

<section id="NoteForm">
    <h2>New note to save</h2>
    @using (Html.BeginForm(new { ReturnUrl = ViewBag.ReturnUrl }))
    {
        @Html.AntiForgeryToken()
        @Html.ValidationSummary()

        <fieldset>
            <legend>Note to save</legend>
            <ol>
                <li>
                    @Html.LabelFor(m => m.Title)
                    @(Html.Kendo().TextBoxFor(m => m.Title)
                        .Name("Title")
                        .Value("")

                    )
                    @Html.ValidationMessageFor(m => m.Title)


                </li>
                <li>
                    @Html.LabelFor(m => m.Text)
                    @(Html.Kendo().EditorFor(m => m.Text)
                        .Name("Text")


                    )

                    @Html.ValidationMessageFor(m => m.Text)

                </li>
                <li>
                    @Html.LabelFor(m => m.languageId)
                    @(Html.Kendo().DropDownListFor(m => m.languageId)
                          .Name("languageId")
                          .DataTextField("Text")
                          .DataValueField("Value")
                          .BindTo((IEnumerable<SelectListItem>)ViewBag.languageslist)
                          .OptionLabel("Select a language")
                    )
                    @Html.ValidationMessageFor(m => m.languageId)
    @*Html.ValidationMessageFor(m => m.Language)*@
                    <!--Without Kendo-->
                    @*Html.DropDownListFor(p => p.languageId, new SelectList(DevelopmentNotesProject.DAL.LanguageAccess.getLanguages().OrderBy(c => c.Value), "Value", "Text"), "Select country", new { @Class = "myDropDownList" })
                        @*Html.ValidationMessageFor(m => m.Language)*@
                </li>

                <li>
                    @Html.LabelFor(m => m.img)
                    @(Html.Kendo().Upload()
                        .Name("files")

                        .Async(a => a
                            .Save("Save", "MyNotes")
                            .Remove("Remove", "MyNotes")


                        )
                            .Events(events => events
                                 .Upload("onSuccess")
                                 .Remove("onRemove"))                              
                    )
                </li>
            </ol>
            <input type="submit" value="Log in" />
        </fieldset>
    }
</section>

@section Scripts {
    @Scripts.Render("~/bundles/jqueryval")
}

现在,图像保存在我项目的 add_data 文件夹中。 使用此代码块:

public ActionResult Save(IEnumerable<HttpPostedFileBase> files)
{
    // The Name of the Upload component is "files"
    if (files != null)
    {
        foreach (var file in files)
        {
            var fileName = Path.GetFileName(file.FileName);
            var physicalPath = Path.Combine(Server.MapPath("~/App_Data"), fileName);

             file.SaveAs(physicalPath);
        }
    }

    // Return an empty string to signify success

    return Content("");
}

问题是当用户提交整个表单时,我将所有表单数据发送到数据库:

    [HttpPost]
    [AllowAnonymous]
    [ValidateAntiForgeryToken]
    public ActionResult Add(NoteForm model, IEnumerable<HttpPostedFileBase> files)
    {
        if (ModelState.IsValid)
        {
            if (OAuthWebSecurity.HasLocalAccount(WebSecurity.GetUserId(User.Identity.Name)))
            {
                try
                {
                    DAL.NoteAccess.insertNote(model.Title, model.Text, model.languageId);
                    return RedirectToAction("Index", "MyNotes");
                }
                catch (MembershipCreateUserException e)
                {
                    //ModelState.AddModelError("", ErrorCodeToString(e.StatusCode));
                }
            }
            else
            {
                return RedirectToAction("Login", "Account");
            }
        }

        // If we got this far, something failed, redisplay form
        return View(model);
    }

我找不到在我的 Noteform 对象(在上面的函数中)中获取图像的解决方案。 顺便说一句,在将图像发送到数据库之前先将图像保存在 app_data 文件夹中更好还是有更好的方法? 感谢您的帮助

编辑: 型号:

[Table("note")]
public class NoteForm
{
    [Required]
    [Display(Name = "Title")]
    public string Title { get; set; }

    [Required]
    [Display(Name = "Text")]
    public string Text { get; set; }

    [Required]
    [Display(Name = "Language")]  
    public int languageId { get; set; }
    [ForeignKey("languageId")]
    [UIHint("LangDropDown")]
    public virtual Language language { get; set; }

    [Display(Name = "Photo")]  
    public byte[] img { get; set; }


    [Key]
    [System.Web.Mvc.HiddenInput(DisplayValue = false)]
    public int id { get; set; }

    [System.Web.Mvc.HiddenInput(DisplayValue = false)]

    public int userId { get; set; }


}

你有什么问题?您将 IEnumerable<HttpPostedFileBase> files 作为您操作的参数。 只需从此 Enumerable 获取文件并将它们以适当的属性设置到您的 NoteForm。

更新 您应该在上传控制中切换文件的异步 post:

.Async(a => a.Save("Save", "MyNotes")
             .Remove("Remove", "MyNotes")

把前面这段代码去掉,你的action的files参数就不会为null了。