任何人都知道有关如何使用实体框架从数据库上载/显示图像的分步教程吗?我已经检查了代码片段,但是我仍然不清楚它是如何工作的。我没有代码,因为除了编写上传表单之外,我也迷路了。任何(我的意思是任何)帮助都将不胜感激。
在旁注中,为什么没有书籍涵盖这一主题?我同时拥有Pro ASP.NET MVC 4和Professional MVC4,他们没有提及它。
任何人都知道有关如何使用实体框架从数据库上载/显示图像的分步教程吗?我已经检查了代码片段,但是我仍然不清楚它是如何工作的。我没有代码,因为除了编写上传表单之外,我也迷路了。任何(我的意思是任何)帮助都将不胜感激。
在旁注中,为什么没有书籍涵盖这一主题?我同时拥有Pro ASP.NET MVC 4和Professional MVC4,他们没有提及它。
Answers:
看看以下
@using (Html.BeginForm("FileUpload", "Home", FormMethod.Post,
new { enctype = "multipart/form-data" }))
{
<label for="file">Upload Image:</label>
<input type="file" name="file" id="file" style="width: 100%;" />
<input type="submit" value="Upload" class="submit" />
}
您的控制器应该有可以接受的动作方法HttpPostedFileBase
;
public ActionResult FileUpload(HttpPostedFileBase file)
{
if (file != null)
{
string pic = System.IO.Path.GetFileName(file.FileName);
string path = System.IO.Path.Combine(
Server.MapPath("~/images/profile"), pic);
// file is uploaded
file.SaveAs(path);
// save the image path path to the database or you can send image
// directly to database
// in-case if you want to store byte[] ie. for DB
using (MemoryStream ms = new MemoryStream())
{
file.InputStream.CopyTo(ms);
byte[] array = ms.GetBuffer();
}
}
// after successfully uploading redirect the user
return RedirectToAction("actionname", "controller name");
}
更新1
如果您想异步使用jQuery上传文件,请尝试使用本文。
处理服务器端(用于多次上传)的代码是;
try
{
HttpFileCollection hfc = HttpContext.Current.Request.Files;
string path = "/content/files/contact/";
for (int i = 0; i < hfc.Count; i++)
{
HttpPostedFile hpf = hfc[i];
if (hpf.ContentLength > 0)
{
string fileName = "";
if (Request.Browser.Browser == "IE")
{
fileName = Path.GetFileName(hpf.FileName);
}
else
{
fileName = hpf.FileName;
}
string fullPathWithFileName = path + fileName;
hpf.SaveAs(Server.MapPath(fullPathWithFileName));
}
}
}
catch (Exception ex)
{
throw ex;
}
此控件还返回图像名称(在javascript回调中),然后您可以使用它在DOM中显示图像。
或者,您可以尝试在MVC 4中进行异步文件上传。
file.SaveAs(path)
如何从该路径删除文件?
这是一个简短的教程:
模型:
namespace ImageUploadApp.Models
{
using System;
using System.Collections.Generic;
public partial class Image
{
public int ID { get; set; }
public string ImagePath { get; set; }
}
}
视图:
创建:
@model ImageUploadApp.Models.Image
@{
ViewBag.Title = "Create";
}
<h2>Create</h2>
@using (Html.BeginForm("Create", "Image", null, FormMethod.Post,
new { enctype = "multipart/form-data" })) {
@Html.AntiForgeryToken()
@Html.ValidationSummary(true)
<fieldset>
<legend>Image</legend>
<div class="editor-label">
@Html.LabelFor(model => model.ImagePath)
</div>
<div class="editor-field">
<input id="ImagePath" title="Upload a product image"
type="file" name="file" />
</div>
<p><input type="submit" value="Create" /></p>
</fieldset>
}
<div>
@Html.ActionLink("Back to List", "Index")
</div>
@section Scripts {
@Scripts.Render("~/bundles/jqueryval")
}
索引(用于显示):
@model IEnumerable<ImageUploadApp.Models.Image>
@{
ViewBag.Title = "Index";
}
<h2>Index</h2>
<p>
@Html.ActionLink("Create New", "Create")
</p>
<table>
<tr>
<th>
@Html.DisplayNameFor(model => model.ImagePath)
</th>
</tr>
@foreach (var item in Model) {
<tr>
<td>
@Html.DisplayFor(modelItem => item.ImagePath)
</td>
<td>
@Html.ActionLink("Edit", "Edit", new { id=item.ID }) |
@Html.ActionLink("Details", "Details", new { id=item.ID }) |
@Ajax.ActionLink("Delete", "Delete", new {id = item.ID} })
</td>
</tr>
}
</table>
控制器(创建)
public ActionResult Create(Image img, HttpPostedFileBase file)
{
if (ModelState.IsValid)
{
if (file != null)
{
file.SaveAs(HttpContext.Server.MapPath("~/Images/")
+ file.FileName);
img.ImagePath = file.FileName;
}
db.Image.Add(img);
db.SaveChanges();
return RedirectToAction("Index");
}
return View(img);
}
希望这会有所帮助:)
filename.LastIndexOf(".")
。希望这会
<input type="file" id="picfile" name="picf" />
<input type="text" id="txtName" style="width: 144px;" />
$("#btncatsave").click(function () {
var Name = $("#txtName").val();
var formData = new FormData();
var totalFiles = document.getElementById("picfile").files.length;
var file = document.getElementById("picfile").files[0];
formData.append("FileUpload", file);
formData.append("Name", Name);
$.ajax({
type: "POST",
url: '/Category_Subcategory/Save_Category',
data: formData,
dataType: 'json',
contentType: false,
processData: false,
success: function (msg) {
alert(msg);
},
error: function (error) {
alert("errror");
}
});
});
[HttpPost]
public ActionResult Save_Category()
{
string Name=Request.Form[1];
if (Request.Files.Count > 0)
{
HttpPostedFileBase file = Request.Files[0];
}
}
Pro ASP MVC 4
该指南的相关SportsStore Tutorial
规定,那么page 292