为什么我的图像不保存在我的数据库中?

Why won't my image be saved in my database?

我正在创建一个 ASP.NET MVC 应用程序,我正在尝试将图像保存到我的数据库中,该图像将附加到汽车上,以便稍后显示。当我 运行 我的代码时,我能够创建一辆新车并将图像保存到一个文件夹中,但是没有信息被添加到图像 table.

的数据库中

这是我的控制器:

[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create(HttpPostedFileBase[] files, [Bind(Include = "CarID,Year,Color,Mileage,Cost,MarketValue,BodyType,Drive,Notes,Available,VinNumber,CarLotID,ModelID")] Car car)
{
        if (ModelState.IsValid)
        {
            foreach (HttpPostedFileBase file in files)
            {
                //Checking file is available to save.  
                if (file != null)
                {
                    var InputFileName = Path.GetFileName(file.FileName);
                    var ServerSavePath = Path.Combine(Server.MapPath("~/CarImages/") + InputFileName);
                    //Save file to server folder  
                    file.SaveAs(ServerSavePath);

                    var image = new Image()
                    {
                        ImagePath = ServerSavePath,
                        Title = ServerSavePath
                    };

                    car.Images.Add(image);
                    //assigning file uploaded status to ViewBag for showing message to user.  
                    ViewBag.UploadStatus = files.Count().ToString() + " files uploaded successfully.";
                }
            }

            db.Cars.Add(car);
            db.SaveChanges();

            return RedirectToAction("Index");
        }

        ViewBag.MakeID = new SelectList(db.Makes, "MakeID", "Name", car.Model?.MakeID);
        ViewBag.ModelID = new SelectList(db.Models, "ModelID", "Name", car.ModelID);
        ViewBag.CarLotID = new SelectList(db.CarLots, "CarLotID", "LotName", car.CarLotID);
        return View(car);
}

这是我的模型 class Image:

public partial class Image
{
    public int ImageID { get; set; }
    public int CarID { get; set; }
    public string Title { get; set; }
    public string ImagePath { get; set; }
    public HttpPostedFileBase ImageFile { get; set; }    
    public virtual Car Car { get; set; }
}

这是我的模型 class Car:

using System;
using System.Collections.Generic;
using System.ComponentModel;

public partial class Car
{
    public int CarID { get; set; }
    public string Year { get; set; }
    public string Color { get; set; }
    public string Mileage { get; set; }
    public decimal Cost { get; set; }
    public string BodyType { get; set; }
    public string Drive { get; set; }
    public string Notes { get; set; }
    public bool Available { get; set; }
    public string VinNumber { get; set; } 
    public int CarLotID { get; set; }
    public int ModelID { get; set; }
    public virtual ICollection<Image> Images { get; set; }
    public virtual CarLot CarLot { get; set; }
    public HttpPostedFileBase[] files { get; set; }
}

这是我的观点

@model IgnitionHub2._0.Models.Car
@using IgnitionHub2._0.Models

@{
    ViewBag.Title = "Create";
    Layout = "~/Views/Shared/_Layout.cshtml";
}

<h2>Create</h2>

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

<div class="form-horizontal">
    <h4>Car</h4>
    <hr />
    @Html.ValidationSummary(true, "", new { @class = "text-danger" })
    <div class="form-group">
        @Html.LabelFor(model => model.Year, htmlAttributes: new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            @Html.EditorFor(model => model.Year, new { htmlAttributes = new { @class = "form-control" } })
            @Html.ValidationMessageFor(model => model.Year, "", new { @class = "text-danger" })
        </div>
    </div>
    <div class="form-group">
        @Html.LabelFor(model => model.files, "Add an Image", htmlAttributes: new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            @Html.TextBoxFor(model => model.files, "", new { @type = "file", @multiple = "multiple" })
            @Html.ValidationMessageFor(model => model.files, "", new { @class = "text-danger" })
        </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>
</div>
}

我从 post 的视图中删除了大部分下拉菜单,因此它不会太长。

请帮忙!谢谢!

如果要将图片保存在目录中,只需将图片的路径保存在数据库中即可。要将图像存储在二进制数据库中,您的图像 model/Entity 应该如下所示。

要将图像存储在二进制数据库中,您的图像模型应如下所示。您必须将在控件中收到的图像转换为字节数组并将其分配给 ImageFile 变量。

更换控制器:

MemoryStream target = new MemoryStream();
file.InputStream.CopyTo(target);
byte[] data = target.ToArray();
image.ImageFile  = data
car.Images.Add(image);

您的模特:

public partial class Image
{
    public int ImageID { get; set; }
    public int CarID { get; set; }
    public string Title { get; set; }
    public string ImagePath { get; set; }
    public byte[] ImageFile { get; set; }    
    public virtual Car Car { get; set; }
}

这是一个像下面这样的工作演示:

型号:

public partial class Car
{
    public Car()
    {
        Images = new List<Image>() { };
    }
    public int CarID { get; set; }
    public string Year { get; set; }
    public string Color { get; set; }
    public string Mileage { get; set; }
    public decimal Cost { get; set; }
    public string BodyType { get; set; }
    public string Drive { get; set; }
    public string Notes { get; set; }
    public bool Available { get; set; }
    public string VinNumber { get; set; }
    public int CarLotID { get; set; }
    public int ModelID { get; set; }
    public virtual List<Image> Images { get; set; }
    public HttpPostedFileBase[] files { get; set; }
}
public partial class Image
{
    public int ImageID { get; set; }
    public int CarID { get; set; }
    public string Title { get; set; }
    public string ImagePath { get; set; }
    public virtual Car Car { get; set; }
    public HttpPostedFileBase[] files { get; set; } 

}

查看:

@model  Car
@using WebApplication2.Models

<h2>Create</h2>

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

    <div class="form-horizontal">
        <h4>Car</h4>
        <hr />
        @Html.ValidationSummary(true, "", new { @class = "text-danger" })
        <div class="form-group">
            @Html.LabelFor(model => model.Year, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.Year, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.Year, "", new { @class = "text-danger" })
            </div>
        </div>
        <div class="form-group">
            @Html.LabelFor(model => model.files, "Add an Image", htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.TextBoxFor(model => model.files, "", new { @type = "file", @multiple = "multiple" })
                @Html.ValidationMessageFor(model => model.files, "", new { @class = "text-danger" })
            </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>
    </div>
}

控制器:

[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create(HttpPostedFileBase[] files,  Car car)
{
    if (ModelState.IsValid)
    {
        foreach (HttpPostedFileBase file in  files)
        {
            //Checking file is available to save.  
            if (file != null)
            {
                var InputFileName = Path.GetFileName(file.FileName);
                var ServerSavePath = Path.Combine(Server.MapPath("~/CarImages/") , InputFileName);
                //Save file to server folder  
                file.SaveAs(ServerSavePath);

                var image = new Image()
                {
                    ImagePath = ServerSavePath,
                    Title = ServerSavePath
                };

                //db.Images.Add(image);
                //  db.SaveChanges();
                car.Images.Add(image);
                //assigning file uploaded status to ViewBag for showing message to user.  
                ViewBag.UploadStatus = files.Count().ToString() + " files uploaded successfully.";
            }
        }

        db.Cars.Add(car);
        db.SaveChanges();

        return RedirectToAction("Index");
    }

    return View(car);
}

结果: