How to upload a image and display on same page in asp.net mvc 4

sanzy picture sanzy · Jun 12, 2013 · Viewed 32.9k times · Source

i have developed a web application using asp.net mvc4 and razor syntax. i need to upload an image using file uploader and display in the same page with details of the image.

as an example there's a "file uploader" and "submit button" in "contact page" of my application. when i upload an image of a person and click the submit button, it should display the image somewhere in the page with its details like image name, size like that.

is there any possible way to achieve that?

here is the code for my controller class

public class FileUploadController : Controller
    {
        //
        // GET: /FileUpload/

        public ActionResult Index()
        {
            return View();
        }
        public ActionResult FileUpload()
        {
            return View();
        }

        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult FileUpload(HttpPostedFileBase uploadFile)
        {
            if (uploadFile.ContentLength > 0)
            {
                string filePath = Path.Combine(HttpContext.Server.MapPath("~/Img/"),
                                               Path.GetFileName(uploadFile.FileName));
            }
            return View();
        }
    }

and here is the code for view

<h2>FileUpload</h2>

     @(Html.BeginForm("FileUpload", "FileUpload",FormMethod.Post, new { enctype = "multipart/form-data" }))
        <input name="uploadFile" type="file" />
        <input type="submit" value="Upload File" />

but how to display on page?

please help.

Answer

Darin Dimitrov picture Darin Dimitrov · Jun 12, 2013

Once you save the uploaded file on the server from your controller action you could pass back the url to this file to the view so that it can be displayed in an <img> tag:

public class FileUploadController : Controller
{
    public ActionResult Index()
    {
        return View();
    }

    public ActionResult FileUpload()
    {
        return View();
    }

    [AcceptVerbs(HttpVerbs.Post)]
    public ActionResult FileUpload(HttpPostedFileBase uploadFile)
    {
        if (uploadFile.ContentLength > 0)
        {
            string relativePath = "~/img/" + Path.GetFileName(uploadFile.FileName);
            string physicalPath = Server.MapPath(relativePath);
            uploadFile.SaveAs(physicalPath);
            return View((object)relativePath);
        }
        return View();
    }
}

Then make your view strongly typed and add an <img> tag that will display the image if the model is not empty:

@model string
<h2>FileUpload</h2>

@using (Html.BeginForm("FileUpload", "FileUpload", FormMethod.Post, new { enctype = "multipart/form-data" })
{
    <input name="uploadFile" type="file" />
    <input type="submit" value="Upload File" />
}

@if (!string.IsNullOrEmpty(Model))
{
    <img src="@Url.Content(Model)" alt="" />
}