MVC将图像保存到DB(使用EF)

时间:2018-01-29 16:49:34

标签: sql asp.net-mvc image entity-framework

我还是MVC的新手,我正在努力将图像上传到我的网络应用程序中的数据库。我已经看过很多关于这个问题的文章,按照说明进行操作,但我仍然遇到以下错误信息:

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

每当我使用[Bind(Exclude =" CompetitionPicture")]时,一切都会正常工作,当然除了#34; CompetitionPicture"不会被包括在内。

我的ViewModel如下所示:

public class PhotoCompetition
{
    public int ID { get; set; }

    public string UserID { get; set; }

    public string FirstName { get; set; }

    public string Email { get; set; }

    public byte[] CompetitionPicture { get; set; }

    [Required]
    [Display(Name = "by checking this box I accept the Terms & Conditions")]
    public bool TermsAndConditionsAccepted { get; set; }

    public DateTime TimeStamp { get; set; }
}

控制器如下:

[HttpPost]
    [ValidateAntiForgeryToken]

    public ActionResult UploadCompetitionPicture(/*[Bind(Exclude = "CompetitionPicture")]*/ PhotoCompetition model)
    {
        string test = Request.Form["CompetitionPicture"];
        byte[] bt = Convert.FromBase64String(test.Split(',')[1]);
        var participation = new PhotoCompetition
        {
            CompetitionPicture = bt
        };

        //    var participation = new PhotoCompetition
        //    {
        //        UserID = User.Identity.GetUserId(),
        //        Email = User.Identity.GetUserName(),
        //        TermsAndConditionsAccepted = model.TermsAndConditionsAccepted,
        //        TimeStamp = DateTime.UtcNow.ToUniversalTime()
        //    };
        //    participation.CompetitionPicture = competitionPicture;
        //    DB.PhotoCompetition.Add(model);
        //    DB.SaveChanges();
        //    return RedirectToAction("Index");
        //}
        return View(model);
    }

和视图:

<section id="photoCompetition" class="manageForm">
    @using (Html.BeginForm("UploadCompetitionPicture", "errandom", FormMethod.Post, new { @id = "photoCompetitionForm", @class = "form-horizontal", @role = "form", @enctype = "multipart/form-data" }))
    {
        @Html.AntiForgeryToken()
        <div id="photoCompetitionSection" class="manageSection">
            <p id="photoCompetitionSectionTitle" class="manageSectionTitle">
                Upload your picture and be selected as our model!
            </p>
            @Html.HiddenFor(m => m.UserID)
            @Html.HiddenFor(m => m.Email)
            @Html.HiddenFor(m => m.FirstName)
            @Html.HiddenFor(m => m.TimeStamp)
            <div id="photoCompetitionProfilePictureArea" class="manageArea row">
                @Html.LabelFor(m => m.CompetitionPicture, new { @id = "photoCompetitionProfilePictureLabel", @class = "manageLabel col-xs-offset-1 col-xs-10 col-sm-offset-1 col-sm-10 col-md-offset-1 col-md-3 col-lg-offset-1 col-lg-4" })
                <a id="photoCompetitionProfilePictureSelectionButton" class="manageField col-xs-offset-1 col-xs-10 col-sm-offset-1 col-sm-10 col-md-offset0 col-md-7 col-lg-offset-0 col-lg-6" href="#">
                    select a file...
                </a>
                @Html.TextBoxFor(m => m.CompetitionPicture, new { @id = "photoCompetitionProfilePictureField", @class = "manageField col-xs-offset-1 col-xs-10 col-sm-offset-1 col-sm-10 col-md-offset-0 col-md-7 col-lg-offset-0 col-lg-6", @name = "CompetitionPicture", @type = "file", @style = "display: none" })
            </div>
            <div id="photoCompetitionTermsAndConditionsArea" class="manageArea row">
                @Html.CheckBoxFor(m => m.TermsAndConditionsAccepted, new { @id = "photoCompetitionTermsAndConditionsField", @class = "photoCompetitionTermsAndConditionsField" })
                @Html.LabelFor(m => m.TermsAndConditionsAccepted, new { @id = "photoCompetitionTermsAndConditionsLabel", @class = "photoCompetitionTermsAndConditionsLabel" })
            </div>
            <script>
                jQuery("#photoCompetitionProfilePictureSelectionButton").click(function () {
                    $("#photoCompetitionProfilePictureField").click();
                });
            </script>
            <script>
                $("#photoCompetitionProfilePictureField").change(function () {
                    var fullFileName = $("#photoCompetitionProfilePictureField").val()
                    $("#photoCompetitionProfilePictureSelectionButton").html(fullFileName.substr(fullFileName.lastIndexOf('\\') + 1));
                });
            </script>
            <div id="photoCompetitionButtonArea" class="manageArea row">
                <input id="photoCompetitionButtonUpload" class="manageButton col-xs-offset-1 col-xs-10 col-sm-offset-1 col-sm-10 col-md-offset-1 col-md-10 col-lg-offset-1 col-lg-10" type="submit" value="Save" />
            </div>
        </div>
    }
</section>

非常感谢您的支持!

1 个答案:

答案 0 :(得分:0)

我在这个问题上坚持了几天,我会简单地解决。

首先:我将图像路径保存为DB中的字符串而不是字节 和图像文件在模型中作为HttpPostedFileBase喜欢:`

public string ProductImage { get; set; }
[Required(ErrorMessage = "Image is required")]
public HttpPostedFileBase ImageFile { get; set; }

在视图中你会写:

&#13;
&#13;
  <div class="form-group">
            <div class="col-md-10">
                <input type="file" name="ImageFile" required />
            </div>
            @Html.ValidationMessageFor(model => model.ImageFile, "", new { @class = "text-danger" })
        </div>
&#13;
&#13;
&#13;

输入名称必须与模型中的名称相似,此处我将其命名为ImageFile

控制器中的

将写入

 public void SaveImage(Product pro)
    {
        string fileName = Path.GetFileNameWithoutExtension(pro.ImageFile.FileName);
        string exetention = Path.GetExtension(pro.ImageFile.FileName);
        fileName = fileName + DateTime.Now.ToString("yymmssfff") + exetention;
        pro.ProductImage = "~/ProductDropBox/" + fileName;
        fileName = Path.Combine(Server.MapPath("~/ProductDropBox/"), fileName);
        pro.ImageFile.SaveAs(fileName);
    }

我使用此功能将图像保存在数据库和为图像创建的文件夹中

最后在行动结果中你会写:

 public ActionResult AddProducts(Product pro)
    {

        if (ModelState.IsValid)
        {
            SetCategories();
            SaveImage(pro);
            pro.UPID = Guid.NewGuid();

            using (db)
            {
                db.Products.Add(pro);
                db.SaveChanges();
            }                
            return RedirectToAction("Index");
        }
        else
        {
            return View("AddProducts",pro);
        }
    }

我希望这个有用