ASP.NET MVC5 - 图像上传到SQL Server 2008R2标准版

时间:2013-10-22 05:44:25

标签: asp.net-mvc sql-server-2008-r2 image-uploading asp.net-mvc-5

我是ASP.NET MVC的半新手,我过去曾经使用过它,但是我没有计划用它来学习我正在研究的一些项目。我知道这个问题已经在互联网上被提出了很多问题,并且有很多解决方案,所以我会尽量保持这一点,尽可能具体地说明上传图像并将它们存储在SQL Server数据库中。

我目前正在使用带有MVC5(VS 2013)的.NET 4.5来完成所有编码。

首先,我找到了一个很棒的教程,让我能够将图像上传到我的SQL Server 2008数据库:http://www.mikesdotnetting.com/Article/125/ASP.NET-MVC-Uploading-and-Downloading-Files

在我弄清楚网站上的功能如何工作后,一切都很顺利,但我遇到的问题是我有多个文本字段,我想将数据包含到SQL Server数据库中,同时包括图像上传功能我根据我在网上找到的教程创建的。

我的代码的第一部分是Models(BeerList.cs)

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data.Entity;
using System.ComponentModel.DataAnnotations;

namespace YBPP_Production.Models
{
public class BeerList
{
    public int ID { get; set; }

    [Required(ErrorMessage = "Name is required")]
    public string Name { get; set; }

    [Required(ErrorMessage = "Company is required.")]
    public string Company { get; set; }

    [Required(ErrorMessage = "Type is required.")]
    public string Type { get; set; }

    [Required(ErrorMessage = "City is required.")]
    public string City { get; set; }

    [Required(ErrorMessage = "State is required.")]
    public string State { get; set; }

    [Required(ErrorMessage = "Country is required")]
    public string Country { get; set; }

    public string ABV { get; set; }
    public string IBU { get; set; }
}

public class Info : DbContext
{
    public DbSet<DBName> MoreDB { get; set; }
}
}

那里列出的字符串是我试图进入我的数据库的文本字段,我可以这样做但是当我尝试混合图像上传功能时,文本将上传或图像将上传取决于我的方式电话。

我的代码的控制器部分(BeerListController.cs)

   // GET: /BeerList/Create
    public ActionResult Create()
    {
        return View();
    }

    // POST: /BeerList/Create
    // To protect from overposting attacks, please enable the specific properties you want to bind to, for 
    // more details see http://go.microsoft.com/fwlink/?LinkId=317598.
    [HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult Create([Bind(Include = "ID,Name,Company,Type,City,State,Country,ABV,IBU")] BeerList beerlist)
    {
        if (ModelState.IsValid)
        {
            db.BeerListDB.Add(beerlist);
            db.SaveChanges();
            return RedirectToAction("Index");
        }

        return View(beerlist);
    }

    public ActionResult FileUpload(HttpPostedFileBase file)
    {
        //Begin the Image Uploading Process
        foreach (string upload in Request.Files)
        {
            if (!Request.Files[upload].HasFile()) continue;

            string mimeType = Request.Files[upload].ContentType;
            Stream fileStream = Request.Files[upload].InputStream;
            string fileName = Path.GetFileName(Request.Files[upload].FileName);
            int fileLength = Request.Files[upload].ContentLength;
            byte[] fileData = new byte[fileLength];
            fileStream.Read(fileData, 0, fileLength);

            const string connect = @"Server=localhost;database=<database-name>;uid=<username-here>;pwd=<there-a-passwordhere>";
            using (var conn = new SqlConnection(connect))
            {
                var qry = "INSERT INTO BeerLists (FileContent, mimeType, FileName) VALUES (@FileContent, @mimeType, @FileName)";
                var cmd = new SqlCommand(qry, conn);
                cmd.Parameters.AddWithValue("@FileContent", fileData);
                cmd.Parameters.AddWithValue("@MimeType", mimeType);
                cmd.Parameters.AddWithValue("@FileName", fileName);
                conn.Open();
                cmd.ExecuteNonQuery();
            }
        }
        return View();
    }

我的代码的视图部分(Create.cshtml)

@model YBPP_Production.Models.BeerList

@{
ViewBag.Title = "Create";
}

<h2>Create</h2>


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

<div class="form-horizontal">
    <h4>BeerList</h4>
    <hr />
    @Html.ValidationSummary(true)

    <div class="form-group">
        @Html.LabelFor(model => model.Name, new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            @Html.EditorFor(model => model.Name)
            @Html.ValidationMessageFor(model => model.Name)
        </div>
    </div>

    <div class="form-group">
        @Html.LabelFor(model => model.Company, new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            @Html.EditorFor(model => model.Company)
            @Html.ValidationMessageFor(model => model.Company)
        </div>
    </div>

    <div class="form-group">
        @Html.LabelFor(model => model.Type, new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            @Html.EditorFor(model => model.Type)
            @Html.ValidationMessageFor(model => model.Type)
        </div>
    </div>

    <div class="form-group">
        @Html.LabelFor(model => model.City, new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            @Html.EditorFor(model => model.City)
            @Html.ValidationMessageFor(model => model.City)
        </div>
    </div>

    <div class="form-group">
        @Html.LabelFor(model => model.State, new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            @Html.EditorFor(model => model.State)
            @Html.ValidationMessageFor(model => model.State)
        </div>
    </div>

    <div class="form-group">
        @Html.LabelFor(model => model.Country, new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            @Html.EditorFor(model => model.Country)
            @Html.ValidationMessageFor(model => model.Country)
        </div>
    </div>

    <div class="form-group">
        @Html.LabelFor(model => model.ABV, new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            @Html.EditorFor(model => model.ABV)
            @Html.ValidationMessageFor(model => model.ABV)
        </div>
    </div>

    <div class="form-group">
        @Html.LabelFor(model => model.IBU, new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            @Html.EditorFor(model => model.IBU)
            @Html.ValidationMessageFor(model => model.IBU)
        </div>
    </div>

    <div class="form-group">
        <p class="control-label col-md-2">Image Upload:</p>
        <div class="col-md-10">
        <input type="file" id="ImageUpload" name="ImageUpload" />
         </div>
    </div>
        <div class="form-group">
        <div class="col-md-offset-2 col-md-10">
            <input type="submit" name="Submit" id="Submit" value="Create" class="btn btn-default" />
        </div>
    </div>
    </div>
}

<div>
    @Html.ActionLink("Back to List", "Index")
</div>

@section Scripts {
   @Scripts.Render("~/bundles/jqueryval")
}

所以我希望得到帮助的是能够将Create和FileUpload的功能合并到一个函数中,以便表单将同时获取文本字段中的文本和获取的图像上传了它。我已经阅读了一些其他人的帖子和代码,他们似乎都有自己的做事方式,但每个人的例子都不包括文本字段或任何其他形式的功能,只是基本的图片上传。

非常感谢您提前解决此问题的任何方向/建议/帮助。

2 个答案:

答案 0 :(得分:1)

您可以创建包含HttpPostedFileBase的模型,然后使用所选文件保存整个表单。

型号:

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

    [Required(ErrorMessage = "Name is required")]
    public string Name { get; set; }

    [Required]
    public HttpPostedFileBase file { get; set; }

}

查看:

@using (Html.BeginForm(null, null, FormMethod.Post, new { enctype = "multipart/form-data" }))
{
@Html.AntiForgeryToken()
<div class="form-horizontal">
    @Html.ValidationSummary(true)

    <div class="form-group">
        @Html.EditorFor(model => model.Name)
        @Html.ValidationMessageFor(model => model.Name)
    </div>

    <div class="form-group">
        <p class="control-label col-md-2">Image Upload:</p>
        <input type="file" id="file" name="file" />
    </div>

    <div class="form-group">
        <input type="submit" name="Submit" id="Submit" value="Create" class="btn btn-default" />
    </div>
</div>

}

控制器:

    [HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult Create(BeerListModel model)
    {
        if (ModelState.IsValid)
        {
            //your logic 
        }

        return View("Create");
    }

答案 1 :(得分:0)

@ Szakus&#39;答案是你想要上传文件的总体方向,但是当你问到时,&#34;对于Controller&#34;的逻辑,我仍然有点困惑。你无意中找到了问题的根源。

我强烈建议您对separation of concerns进行一些研究。将原始SQL代码放在控制器中并不是一个好主意,并且会将您的应用程序打开到其他许多问题中。

我知道这并没有真正回答你的问题但是现在你已经到了现在我可以告诉你,古老的格言,&#34;一盎司的预防值得一磅治愈&#34;将为您节省大量的麻烦。

如果你想看一个非常好的.net MVC项目的例子,你可以用它作为模板来建立你的技能,我会推荐开源购物车nopCommerce