【问题标题】:How do I upload images in ASP.NET MVC?如何在 ASP.NET MVC 中上传图像?
【发布时间】:2011-06-18 03:14:35
【问题描述】:

如何在 ASP.NET MVC 3.0 中上传图片以进入~/Content/Images

【问题讨论】:

标签: asp.net-mvc file-upload upload asp.net-mvc-3


【解决方案1】:

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);
        }
    }
}

【讨论】:

    【解决方案2】:

    如果您想在 ASP.NET MVC 中上传图片,请尝试以下问题:

    如果您想使用 ASP.NET 控件来上传图像,这会破坏 MVC 的关注点分离。有upload helpers available

    【讨论】:

      猜你喜欢
      • 2012-05-11
      • 2019-01-19
      • 2017-10-20
      • 1970-01-01
      • 2018-08-28
      • 2015-12-04
      • 2010-11-25
      • 2012-01-11
      • 2018-09-04
      相关资源
      最近更新 更多