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

4

11

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.

Gayomart answered 12/6, 2013 at 8:44 Comment(1)
is there any possible way to achieve that? - yes, of course. Where did you get so far? What research you did and what code did you attempt to write? What difficulties did you encounter with this code that you would like to ask about?Humor
H
17

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="" />
}
Humor answered 12/6, 2013 at 9:4 Comment(4)
Why wouldn't I take the time? Once the OP updated his answer with code sample of what he tried so far, I immediately removed my downvote from his question and answered it.Humor
@DarinDimitrov i used the code you given and its working. thanx anywy.. :) but one thing, i have not created any model for this.. and i want to resize the image before display and how to do that? do i have to use the model for that or what?Gayomart
You could resize the image on the server before storing it on the disk. And then pass the resized filename to the client.Humor
I saw that he put his code in the comment and I put it in his answer for him.Writing
M
3

in HTML:

<input type='file' onchange="readURL(this);" />

Javascript/JQuery through the Type FileReader

if (input.files && input.files[0]) {
    var reader = new FileReader();
    reader.onload = function (e) {
            $('#blah').attr('src', e.target.result);
        }
        reader.readAsDataURL(input.files[0]);
    }

where input is the <input type="file"> element if you use AjaxToolKit AsyncFileUpload, you can get the input using: fileUploadElement.get_inputFile()

Please refere to: how to preview a image before and after upload?

Mathura answered 29/1, 2014 at 14:2 Comment(0)
R
1

To display uploaded image on page, you will have to save the image somewhere, then reference corresponding URL in the <img> tag.

If you save it on disk within the website location, you can reference it by the URL that corresponds to the save location (so if you save it to Img the relative URL would be ~/Img/imagename).

If you save it to the database, you'll have to provide a separate action method or HttpHandler to get it.

Reinforcement answered 12/6, 2013 at 9:4 Comment(1)
yes andrey. its the logic what i couldn't go through. thanx for the help.. :)Gayomart
W
-1

So here's the typical flow for something like this.

  1. You start out on the Index action which you can see the fileupload control.
  2. The fileupload is in a form that will submit to your FileUpload action.
  3. Inside your FileUpload action you do your thing and at the end you return RedirectToAction("Index");

Now obviously there's more to do. You need to save that file somewhere, let's say in a directory called UploadStuff.

Within your index action you will read that directory for your file.

Again this is to get you going. In the real world you're storing a reference to this file in say a database and querying that database based off of some unique identifier such as a userId or a productId to figure out which uploaded items get shown on the index view.

Writing answered 12/6, 2013 at 9:3 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.