Upload images to the index with MVC 4 C #


I have in my view "Upload" the following code:

<form action="" method="post" enctype="multipart/form-data">

<label for="file">Filename:</label>
<input type="file" name="file" id="file" />

<input type="submit" />

And in my controller "SubidaController" the following

public ActionResult Subida()
        return View();

I need that from the form of my view I can upload an image to then go to the index and see it there. That is to say that when uploading an image it must be saved inside a physical directory of my project so when restarting or reloading the page the images are not lost. I've searched I've tried methods that use sites like this link but I have not achieved what I need.


Here I found the way to do it, the only problem I have is that they are not shown on my homepage, they are only saved in the "images" folder of my project link

Upload View



asked by Lucas. D 16.06.2016 в 20:32

1 answer


Welcome to SOes, there are different ways to achieve what you say, here's a simple one:

In the controller where you perform GET of Index

ViewBag.Imagen = Server.MapPath("~") + @"Content\Images\ImagenAMostrar.png";

In the view

 <img src="@ViewBag.Imagen" alt="IMAGES" />

Successes and blessings with the programming, give it all the power 2.0! You're on the right track: D


The Uploads folder I have in the root of the project:

On the controller Home :

public ActionResult Index()
        List<string> listaRutaImagenes = new List<string>();
        var carpeta = Server.MapPath("~") + @"Uploads";
        //Necesitas: using System.IO; para realizar esto
        DirectoryInfo d = new DirectoryInfo(carpeta);
        //Obtenemos todos los .jpg
        FileInfo[] Files = d.GetFiles("*.jpg");          
        //Recorremos la carpeta
        foreach (FileInfo file in Files)
        ViewBag.lista = listaRutaImagenes;
        return View();

In the view: Views \ Home \ Index:

@foreach (var item in ViewBag.lista)
        <img src="~/Uploads/@item" width="300" height="300" alt="" />

Resulting in:

answered by 16.06.2016 / 21:04