最後一步我一直在苦苦掙扎,將圖像上傳到文件夾。我沒有保存數據庫的路徑。我現在要把它全部放在一邊,現在圖像信息和圖像路徑被保存到數據庫,但圖像本身不會出現在IMage文件夾中。我在索引和創建視圖之間跳轉。預先感謝所有幫助和對我的英語感到抱歉。/將圖像上傳到文件夾mvc 5代碼優先
Create.cshtml
@using (Html.BeginForm())
{
@Html.AntiForgeryToken()
<h2>@ViewBag.Message</h2>
<p>
To learn more about ASP.NET MVC visit <a href="http://asp.net/mvc" title="ASP.NET MVC Website">http://asp.net/mvc</a>.
</p>
<p>
@using (Html.BeginForm("Create", "Imagefiles", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
@Html.LabelFor(model => model.BildInfo, htmlAttributes: new { @class = "control-label col-md-2" })
@Html.EditorFor(model => model.BildInfo, new { htmlAttributes = new { @class = "form-control" } })
<label for="file">Upload Image:</label>
<input type="file" name="file" id="file" />
<input type="submit" value="Upload Image" />
}
</p>
}
INDEX.cshtml
@model IEnumerable<Upload.Models.Imagefiles>
@{
ViewBag.Title = "Index";
}
<h2>Index</h2>
<p>
@Html.ActionLink("Create New", "Create")
</p>
<table class="table">
<tr>
<th>
@Html.DisplayNameFor(model => model.file)
</th>
<th>
@Html.DisplayNameFor(model => model.BildInfo)
</th>
<th></th>
</tr>
@foreach (var item in Model) {
<tr>
<td>
@Html.DisplayFor(modelItem => item.file)
</td>
<td>
@Html.DisplayFor(modelItem => item.BildInfo)
</td>
<td><img src="~/Images/@item.file" width="100" height="100" /></td>
<td>
@Html.ActionLink("Edit", "Edit", new { id=item.FilID }) |
@Html.ActionLink("Details", "Details", new { id=item.FilID }) |
@Html.ActionLink("Delete", "Delete", new { id=item.FilID })
</td>
</tr>
}
</table>
IMAGEFILESCONTROLLER.CS
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create([Bind(Include = "FilID,file,BildInfo")] Imagefiles imagefiles, HttpPostedFileBase imagesfiles)
{
if (ModelState.IsValid)
{
db.Imagefiles.Add(imagefiles);
db.SaveChanges();
return RedirectToAction("Index");
}
var path = Path.Combine(Server.MapPath("~/Content/Files/"), imagesfiles.FileName);
var data = new byte[imagesfiles.ContentLength];
imagesfiles.InputStream.Read(data, 0, imagesfiles.ContentLength);
using (var sw = new FileStream(path, FileMode.Create))
{
sw.Write(data, 0, data.Length);
}
return RedirectToAction("Index");
我很抱歉地說,但一切工作正常,除了該文件不會被保存到FILES文件夾.. :(感謝所有類型的幫助.. –