【发布时间】:2011-06-18 03:14:35
【问题描述】:
如何在 ASP.NET MVC 3.0 中上传图片以进入~/Content/Images?
【问题讨论】:
标签: asp.net-mvc file-upload upload asp.net-mvc-3
如何在 ASP.NET MVC 3.0 中上传图片以进入~/Content/Images?
【问题讨论】:
标签: asp.net-mvc file-upload upload asp.net-mvc-3
HTML 上传文件 ASP MVC 3.
模型:(请注意,FileExtensionsAttribute 在 MvcFutures 中可用。它将验证客户端和服务器端的文件扩展名。)
public class ViewModel
{
[Required, Microsoft.Web.Mvc.FileExtensions(Extensions = "csv", ErrorMessage = "Specify a CSV file. (Comma-separated values)")]
public HttpPostedFileBase File { get; set; }
}
HTML 视图:
@using (Html.BeginForm("Action", "Controller", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
@Html.TextBoxFor(m => m.File, new { type = "file" })
@Html.ValidationMessageFor(m => m.File)
}
控制器动作:
[HttpPost]
public ActionResult Action(ViewModel model)
{
if (ModelState.IsValid)
{
// Use your file here
using (MemoryStream memoryStream = new MemoryStream())
{
model.File.InputStream.CopyTo(memoryStream);
}
}
}
【讨论】:
如果您想在 ASP.NET MVC 中上传图片,请尝试以下问题:
如果您想使用 ASP.NET 控件来上传图像,这会破坏 MVC 的关注点分离。有upload helpers available。
【讨论】: