2

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

George Stocker
  • 57,289
  • 29
  • 176
  • 237
Viktor Vice
  • 223
  • 1
  • 2
  • 13
  • 1
    possible duplicate of [Uploading an image using ASP.NET MVC](http://stackoverflow.com/questions/1379558/uploading-an-image-using-asp-net-mvc) – George Stocker Jan 30 '11 at 15:28

2 Answers2

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);
        }
    }
}
Paulius Zaliaduonis
  • 5,059
  • 3
  • 28
  • 23
1

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

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.

Community
  • 1
  • 1
George Stocker
  • 57,289
  • 29
  • 176
  • 237