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

问题描述 投票:0回答:1

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

这是我的控制器:

[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);
}

这是我的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; }
}

这是我的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>
}

我从帖子的视图中删除了大多数下拉菜单,因此它不会太长。

请帮助!谢谢!

asp.net asp.net-mvc asp.net-core asp.net-mvc-4 file-upload
1个回答
0
投票

如果要将图片保留在目录中,只需将图片的路径保留在数据库中。要将图像存储在二进制数据库中,您的图像模型/实体应如下所示。

要将图像存储在二进制数据库中,您的图像模型应如下所示。您必须将控件中收到的图像转换为字节数组,并将其分配给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; }
}
© www.soinside.com 2019 - 2024. All rights reserved.