我想在我的MVC 4.0项目中添加上传照片功能,请你告诉我该怎么做。我正在使用MVC 4.o而对于Photo选项我想提供文件/图片上传。这是我的代码
@model WebCart.Category
@{
ViewBag.Title = "Create";
}
<h2>Create</h2>
@using (Html.BeginForm("Create", "Category", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
@Html.ValidationSummary(true)
<fieldset>
<legend>Category</legend>
<div class="editor-label">
@Html.LabelFor(model => model.Title)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.Title)
@Html.ValidationMessageFor(model => model.Title)
</div>
<div class="editor-label">
@Html.LabelFor(model => model.Description)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.Description)
@Html.ValidationMessageFor(model => model.Description)
</div>
<div class="editor-label">
@Html.LabelFor(model => model.Photo)
</div>
<div class="editor-field">
<input name="PhotoFile" id="File" type="file"/>
</div>
<p>
<input type="submit" value="Create" />
</p>
</fieldset>
}
<div>
@Html.ActionLink("Back to List", "Index")
</div>
@section Scripts {
@Scripts.Render("~/bundles/jqueryval")
}
[HttpPost]
[ValidateInput(false)]
public ActionResult Create(Category category)
{
if (ModelState.IsValid)
{
db.Categories.AddObject(category);
db.SaveChanges();
return RedirectToAction("Index");
}
return View(category);
}
答案 0 :(得分:1)
您的控制器操作可能需要额外的PhotoFile
参数:
[HttpPost]
[ValidateInput(false)]
public ActionResult Create(Category category, HttpPostedFileBase photoFile)
{
if (ModelState.IsValid)
{
// you could manipulate the PhotoFile parameter here
// for example let's store the uploaded file to a folder on the server
if (photoFile != null && photoFile.ContentLength > 0)
{
var fileName = Path.GetFileName(photoFile.FileName);
var path = Path.Combine(Server.MapPath("~/App_Data"), fileName);
photoFile.SaveAs(path);
}
db.Categories.AddObject(category);
db.SaveChanges();
return RedirectToAction("Index");
}
return View(category);
}
或者,如果您想将上传的文件作为字节数组读取,可以使用以下内容:
byte[] photo = new byte[photoFile.InputStream.Length];
photoFile.InputStream.Read(photo, 0, photo.Length);
// Now you could assign the byte array to some property of your model
// and persist it into the database (even if this is a bad practice -
// it would be more correct to store the photo on the file system and
// only store the full path to the photo in the database)
在ASP.NET MVC中上传文件必读文章如下:http://haacked.com/archive/2010/07/16/uploading-files-with-aspnetmvc.aspx