How do I upload images in ASP.NET MVC?

2019-07-20 05:12发布

问题:

How do I upload images to go into ~/Content/Images in ASP.NET MVC 3.0?

回答1:

If you want to upload images in ASP.NET MVC, try these questions:

  • Simple Image Upload in ASP.NET MVC
  • Uploading an image in ASP.NET MVC

If you're wanting to use an ASP.NET control to upload images, that breaks the separation of concerns for MVC. There are upload helpers available.



回答2:

HTML Upload File ASP MVC 3.

Model: (Note that FileExtensionsAttribute is available in MvcFutures. It will validate file extensions client side and server side.)

public class ViewModel
{
    [Required, Microsoft.Web.Mvc.FileExtensions(Extensions = "csv", ErrorMessage = "Specify a CSV file. (Comma-separated values)")]
    public HttpPostedFileBase File { get; set; }
}

HTML View:

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

Controller action:

[HttpPost]
public ActionResult Action(ViewModel model)
{
    if (ModelState.IsValid)
    {
        // Use your file here
        using (MemoryStream memoryStream = new MemoryStream())
        {
            model.File.InputStream.CopyTo(memoryStream);
        }
    }
}