我是MVC的半新手 ASP.NET 我过去使用过它,但没有达到我一直计划使用它的程度,并为我正在从事的一些项目学习。 我知道这个问题在互联网上被问了很多,并且有很多解决方案,所以我将尝试在上传图像并将其存储在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 数据库中,同时包括我根据我在网上找到的教程创建的图像上传功能。
我的代码的第一部分是模型(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")
}
因此,我希望得到帮助的是能够将创建和FileUpload
功能合并到一个函数中,以便表单将同时包含文本字段中的文本和随之上传的图像。我读过一堆其他人的帖子和代码,他们似乎都有自己的做事方式,但每个示例都不包含文本字段或任何其他表单函数,只是基本的图像上传。
提前非常感谢您对此问题的任何指示/建议/帮助。
您可以创建包含 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");
}
答案是你想要上传文件的总体方向,但是当你问"我仍然有点困惑我应该把什么作为控制器的逻辑"时,你无意中找到了问题的根源。
我强烈建议你做一些关于关注点分离的研究。 将原始 SQL 代码放入控制器中不是一个好主意,并且会使您的应用程序面临许多其他问题。
我知道这并不能真正回答你的问题,但有了你现在的位置,我可以告诉你,古老的格言,"一盎司的预防胜过一磅的治疗"将为你节省重大的头痛。
如果你想看到一个非常好的.net MVC项目的例子,你可以用它作为培养技能的模板,我会推荐开源购物车nopCommerce。