0

我是ASP.NET MVC的新手,我已經在過去使用它,但沒有達到我一直計劃使用它的程度,從我正在學習的一些項目中學習。我知道這個問題已經在互聯網上提出了很多問題,並且有很多解決方案,所以我會盡量保持上傳圖像並將它們存儲在SQL Server數據庫中。ASP.NET MVC5 - 圖像上傳到SQL Server 2008R2標準

我目前使用.NET 4.5與MVC5(VS 2013)來做我所有的編碼。

首先,我發現了一個偉大的教程,讓我起來,並能夠將圖像上傳到我的SQL Server 2008數據庫運行:之後我想通了的功能如何從網站工作http://www.mikesdotnetting.com/Article/125/ASP.NET-MVC-Uploading-and-Downloading-Files

一切都很正常,但我遇到的問題是我有多個文本字段,我想從SQL Server數據庫中包含數據,幷包含一個基於我在線發現的教程創建的圖像上載功能。

我的代碼的第一部分是模型(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的功能合併爲一個函數,以便表單將文本字段中的文本和隨其一起上傳的圖像一起取出。我讀過一堆其他人的帖子和代碼,他們似乎都有自己的做事方式,但每個人的例子都不包括文本字段或任何其他形式的功能,只是基本的圖片上傳。

非常感謝您對此問題的任何方向/建議/幫助。

+0

您是否設法使此工作?這正是我現在想要做的。 – Rick

回答

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"); 
    } 
+0

謝謝您的信息;就我對控制器的邏輯而言,我仍然有點困惑。我知道大概的想法是讀取將要上傳的文件(圖像)的字節,然後我想我需要在我的原始創建中使用數據庫提交功能。有可能解釋一些進一步的細節,我可能在控制器中尋找什麼邏輯。再次感謝你。 – EvilLinux

0

@Szakus'答案是你想要去相對於總體方向上傳但是當你問到「我仍然有點困惑,就我的控制器邏輯而言」,你無意中得到了問題的根源。

我強烈建議你對separation of concerns做一些研究。將原始SQL代碼放入您的控制器中並不是一個好主意,它會將您的應用程序打開到其他問題的主機中。

我知道這並不是真的答案你的問題,但一直在你現在的位置我可以告訴你,「一盎司的預防值得一磅藥」值得稱讚,馬路。

如果你想看到一個很好的.net MVC項目的例子,你可以使用它作爲模板來構建你的技能,我會推薦開源購物車nopCommerce