MVC3/EF4.1 将 HttpPostedFileBase 绑定到模型并添加到 DB

发布于 2024-12-03 11:24:24 字数 2553 浏览 1 评论 0原文

我有一个 ActionResult 它将数据绑定到模型并将其添加到数据库中。现在我想要的是有一个文件上传器,以及用于存储文件并将其文件名添加到数据库的 ActionResult(以便我可以稍后显示文件/图像)。最好的方法是什么?这是我到目前为止所得到的(它可以存储文件,但我不确定 EF 有多智能,以及数据类型有多复杂):

模型类:

    public class Annonce
{
    public int Id { get; set; }
    public string Company { get; set; }
    public string Size { get; set; }
    public IEnumerable<HttpPostedFileBase> FileUpload { get; set; }
}

视图(使用 mircosoft.web.helpers):

    @using (Html.BeginForm("Create", "Annonce", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
    @Html.ValidationSummary(true)
    <fieldset>
        <legend>Annonce</legend>

        <div class="editor-label">
            @Html.LabelFor(model => model.Company)
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.Company)
            @Html.ValidationMessageFor(model => model.Company)
        </div>

        <div class="editor-label">
            @Html.LabelFor(model => model.Size)
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.Size)
            @Html.ValidationMessageFor(model => model.Size)
        </div>

        <div class="editor-label">
            @Html.LabelFor(model => model.FileUpload)
        </div>
        <div class="editor-field">
 @FileUpload.GetHtml(uploadText: "Opret")
        </div>
    </fieldset>

控制器:

[HttpPost]
    public ActionResult Create(Annonce annonce)
    {
        if (ModelState.IsValid)
        {                
            //System.IO stuff
            foreach (var file in annonce.FileUpload)
            {
                if (file.ContentLength > 0)
                {
                    var fileName = Path.GetFileName(file.FileName);
                    var path = Path.Combine(Server.MapPath("~/App_Data/uploads"), fileName);
                    file.SaveAs(path);

                }
            }
            //Database stuff
            db.Annoncer.Add(annonce);
            db.SaveChanges();
            return RedirectToAction("Index");  
        }

        return View(annonce);
    }

这可以很好地存储文件。现在我想要的是将 file.FileName 存储在数据库中。起初,我认为 EF 会简单地将文件或文件名从 model.FileUpload 绑定到数据库。但我猜数据类型太复杂了?所以我想制作一个 list 并在那里添加 file.FileName 吗?或者也许创建一个全新的实体/表,其中所有文件名都存储为带有引用 ID 的字符串? 有什么建议吗?

I have an ActionResult which binds data to the model and adds it the the DB. Now what I want, is to have a file uploader, and the ActionResult to store the files and adding their FileName to the DB (so I can show the files/images at a later point). What is the best approach? Here is what I got so far (It can store the files, but im not sure how intelligent EF is, and how complex the datatypes can be):

The model class:

    public class Annonce
{
    public int Id { get; set; }
    public string Company { get; set; }
    public string Size { get; set; }
    public IEnumerable<HttpPostedFileBase> FileUpload { get; set; }
}

The view (using mircosoft.web.helpers):

    @using (Html.BeginForm("Create", "Annonce", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
    @Html.ValidationSummary(true)
    <fieldset>
        <legend>Annonce</legend>

        <div class="editor-label">
            @Html.LabelFor(model => model.Company)
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.Company)
            @Html.ValidationMessageFor(model => model.Company)
        </div>

        <div class="editor-label">
            @Html.LabelFor(model => model.Size)
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.Size)
            @Html.ValidationMessageFor(model => model.Size)
        </div>

        <div class="editor-label">
            @Html.LabelFor(model => model.FileUpload)
        </div>
        <div class="editor-field">
 @FileUpload.GetHtml(uploadText: "Opret")
        </div>
    </fieldset>

The controller:

[HttpPost]
    public ActionResult Create(Annonce annonce)
    {
        if (ModelState.IsValid)
        {                
            //System.IO stuff
            foreach (var file in annonce.FileUpload)
            {
                if (file.ContentLength > 0)
                {
                    var fileName = Path.GetFileName(file.FileName);
                    var path = Path.Combine(Server.MapPath("~/App_Data/uploads"), fileName);
                    file.SaveAs(path);

                }
            }
            //Database stuff
            db.Annoncer.Add(annonce);
            db.SaveChanges();
            return RedirectToAction("Index");  
        }

        return View(annonce);
    }

This stores the files just fine. Now what I want, is file.FileName to be stores in the db. At first, I though EF would simply bind the files or filenames from model.FileUpload to the db. But I guess the datatype is too complex? So I though of making a list<HttpPostedFileBase> and adding the file.FileName there? Or maybe create an entire new entity/table where all the filenames are stored as strings with a reference-Id?
Any suggestions?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

静水深流 2024-12-10 11:24:24

我认为您不想将实际文件内容保存在数据库中。
所以我会做类似的事情:

public class AnnonceFile
{
    public string filename {get;set;}
}

public class Annonce
{
    public int Id { get; set; }
    public string Company { get; set; }
    public string Size { get; set; }
    public ICollection<AnnonceFile> Filenames{ get; set; }
}


        //System.IO stuff
        foreach (var file in files)
        {
            if (file.ContentLength > 0)
            {
                var fileName = Path.GetFileName(file.FileName);
                var path = Path.Combine(Server.MapPath("~/App_Data/uploads"), fileName);
                file.SaveAs(path);
                annonce.Filenames.Add( new AnnonceFile {filename = path});

            }
        }
        //Database stuff
        db.Annoncer.Add(annonce);
        db.SaveChanges();
        return RedirectToAction("Index");  
  1. 您需要调整之后保存的路径,因为 asp.net 不允许您从 App_Data 文件夹提供文件。
  2. public ICollection; Filenames 只是为了给您一个想法,但您可能需要在 ICollection中更改它。文件

I don't think you want to save the actual file contents in the database.
So I would do something like:

public class AnnonceFile
{
    public string filename {get;set;}
}

public class Annonce
{
    public int Id { get; set; }
    public string Company { get; set; }
    public string Size { get; set; }
    public ICollection<AnnonceFile> Filenames{ get; set; }
}


        //System.IO stuff
        foreach (var file in files)
        {
            if (file.ContentLength > 0)
            {
                var fileName = Path.GetFileName(file.FileName);
                var path = Path.Combine(Server.MapPath("~/App_Data/uploads"), fileName);
                file.SaveAs(path);
                annonce.Filenames.Add( new AnnonceFile {filename = path});

            }
        }
        //Database stuff
        db.Annoncer.Add(annonce);
        db.SaveChanges();
        return RedirectToAction("Index");  
  1. You need to adjust the path saved to afterwards, since asp.net won't allow you to serve files from the App_Data folder.
  2. the public ICollection<string> Filenames is just to give you an idea, but you probably need to change that in ICollection<FileEntity> Files.
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文