Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 596
sanzy Avatar asked Jun 12 '13 08:06

sanzy


1 Answers

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?

like image 138
Muhammad Omar ElShourbagy Avatar answered Sep 22 '22 08:09

Muhammad Omar ElShourbagy