C# MVC 4 ASP.net,如何将文件插入到数据库存储中(二进制)

Wea*_*nie 2 c# asp.net asp.net-mvc httppostedfilebase asp.net-mvc-4

有人介意指导我,如何将文件保存到我的数据库中,并在可能的情况下检索它,我还是这个 C# 和 MVC 4 的新手。我的数据库分配包含一个属性调用 FileLocation,它是 varBinary (MAX)。

模型

 public partial class Assignment
{
    public Assignment()
    {
        this.CourseAvailables = new HashSet<CourseAvailable>();
    }



    public string AssignmentID { get; set; }
    public Nullable<System.DateTime> SubmissionDate { get; set; }
    public string Status { get; set; }
    [Range(0,100, ErrorMessage="Only Value between 0-100 is accepted.")]
    public Nullable<decimal> Mark { get; set; }
    public string Comments { get; set; }
    public byte[] FileLocation { get; set; }

    public virtual ICollection<CourseAvailable> CourseAvailables { get; set; }
}
}
Run Code Online (Sandbox Code Playgroud)

控制

[HttpPost]
    public ActionResult Create(Assignment assignment)
    {

        if (ModelState.IsValid)
        {
            db.Assignments.Add(assignment);
            db.SaveChanges();
            return RedirectToAction("Index");
        }
        return View(assignment);
    }
Run Code Online (Sandbox Code Playgroud)

看法

@using(Html.BeginForm("Create","Assignment",FormMethod.Post,new {enctype="multipart/form-data"}))
{
...
<div class="editor-field">
    <%: Html.TextBoxFor(model => model.FileLocation, new { type="file"})%>
    <%: Html.ValidationMessageFor(model => model.FileLocation) %>
</div>
...
}
Run Code Online (Sandbox Code Playgroud)

Rad*_*umb 5

您需要在这里进行更多处理。上传的文件作为一个HttpPostedFileBase,而不是一个,byte[]所以你需要byte[]从 HttpPostedFileBase 的 InputStream 中获取,如下所示:

[HttpPost]
public ActionResult Create(Assignment assignment)
{
    if(Request.Files != null && Request.Files.Count == 1)
    {
        var file = Request.Files[0];
        if (file != null && file.ContentLength > 0)
        {
            var content = new byte[file.ContentLength];
            file.InputStream.Read(content, 0, file.ContentLength);
            assignment.FileLocation = content;

            // the rest of your db code here
        }
    }
    return RedirectToAction("Create");    
}
Run Code Online (Sandbox Code Playgroud)

PS 该模型看起来很像一个实体对象。使用 Entity 对象作为模型是一个非常糟糕的主意。尝试制作一个中间模型并使用它来呈现您的数据。

编辑

在你看来,改变这一点:

<%: Html.TextBoxFor(model => model.FileLocation, new { type="file"})%>
Run Code Online (Sandbox Code Playgroud)

对此:

<input type="file" id="file" name="file" />
Run Code Online (Sandbox Code Playgroud)

您收到的错误是因为模型绑定器错误地尝试将页面上的 FileLocation 字段(HttpPostedFileBase 类型)绑定到模型中的 FileLocation 字段(byte[] 类型)。