How to upload image in ASP.NET MVC 4 using ajax or any other technique without postback?

60,981

Solution 1

HTML Code

<input type="file"  id="uploadEditorImage"  />

Javascript Code

$("#uploadEditorImage").change(function () {
    var data = new FormData();
    var files = $("#uploadEditorImage").get(0).files;
    if (files.length > 0) {
        data.append("HelpSectionImages", files[0]);
    }
    $.ajax({
        url: resolveUrl("~/Admin/HelpSection/AddTextEditorImage/"),
        type:"POST",
        processData: false,
        contentType: false,
        data: data,
        success: function (response) {
           //code after success

        },
        error: function (er) {
            alert(er);
        }

    });
});

Code in MVC controller

if (System.Web.HttpContext.Current.Request.Files.AllKeys.Any())
        {
            var pic = System.Web.HttpContext.Current.Request.Files["HelpSectionImages"];
        }

Solution 2

There are two ways to post files (images) asynchronously If your target browsers support file api, you can use the following: HTML:

<input type="file" name="etlfileToUpload" id="etlfileToUpload"  />

JavaScript

// Call this function on upload button click after user has selected the file 
function UploadFile() {
    var file = document.getElementById('etlfileToUpload').files[0];
    var fileName = file.name;    
    var fd = new FormData();    
    fd.append("fileData", file);    
    var xhr = new XMLHttpRequest();
    xhr.upload.addEventListener("progress", function (evt) { UploadProgress(evt); }, false);
    xhr.addEventListener("load", function (evt) { UploadComplete(evt); }, false);
    xhr.addEventListener("error", function (evt) { UploadFailed(evt); }, false);
    xhr.addEventListener("abort", function (evt) { UploadCanceled(evt); }, false);
    xhr.open("POST", "{URL}", true); 
    xhr.send(fd);
}


function UploadProgress(evt) {
    if (evt.lengthComputable) {
        var percentComplete = Math.round(evt.loaded * 100 / evt.total);
        $("#uploading").text(percentComplete + "% ");        
    }
}

function UploadComplete(evt) {
    if (evt.target.status == 200)
        alert(evt.target.responseText);
    else {
        alert("Error Uploading File");
    }
}

function UploadFailed(evt) {    
    alert("There was an error attempting to upload the file.");
}

function UploadCanceled(evt) {    
    alert("The upload has been canceled by the user or the browser dropped the connection.");
}

or you can use swf tools like uploadify

Solution 3

I personally don't prefer to use any kind of third party tool other than java script, css or html. I will go with first approach shown by UmairP. But if you want to spare your self for writting to much of a code. Here is a nice plugin of jquery.

And also there is a demo for asp.net mvc with this plugin.

Please have a look. Let me know if any further information needed.

Solution 4

Try this its working for me

   <input type="file" name="Upload" id="Upload" />

$('#Upload').change(function () {
    debugger;
    var file = document.getElementById('Upload').files[0];
    var fileName = file.name;
    var fd = new FormData();
    fd.append("fileData", file);
    fd.append("key", '@Model.Id');

    var xhr = new XMLHttpRequest();
    xhr.upload.addEventListener("progress", function (evt) { UploadProgress(evt); }, false);
    xhr.addEventListener("load", function (evt) { UploadComplete(evt); }, false);
    xhr.addEventListener("error", function (evt) { UploadFailed(evt); }, false);
    xhr.addEventListener("abort", function (evt) { UploadCanceled(evt); }, false);
    xhr.open("POST", "/ImageHandler.ashx", true);
    xhr.send(fd);
});


function UploadProgress(evt) {
    if (evt.lengthComputable) {
        var percentComplete = Math.round(evt.loaded * 100 / evt.total);
        //$("#uploading").text(percentComplete + "% ");
    }
}

function UploadComplete(evt) {
    //if (evt.target.status == 200)
        //alert(evt.target.responseText);
    //else {
    //   // alert("Error Uploading File");
    //}
}

function UploadFailed(evt) {
   // alert("There was an error attempting to upload the file.");
}

function UploadCanceled(evt) {
    //alert("The upload has been canceled by the user or the browser dropped the connection.");
}

Handler:

public class ImageHandler : IHttpHandler
{
    public void ProcessRequest(HttpContext context)
    {
        //context.Response.ContentType = "text/plain";
        //context.Response.Write("Hello World");]



        string filePath = Constants.ImageFolderPath;

        //write your handler implementation here.
        if (context.Request.Files.Count <= 0)
        {
            context.Response.Write("No file uploaded");
        }
        else
        {
            for (int i = 0; i < context.Request.Files.Count; ++i)
            {
                HttpPostedFile file = context.Request.Files[i];
                if (context.Request.Form != null)
                {
                    string imageid = context.Request.Form.ToString();
                    imageid = imageid.Substring(imageid.IndexOf('=') + 1);

                    if (file != null)
                    {
                        string ext = file.FileName.Substring(file.FileName.IndexOf('.'));
                        if (ext.ToLower().Contains("gif") || ext.ToLower().Contains("jpg") || ext.ToLower().Contains("jpeg") || ext.ToLower().Contains("png"))
                        {

                            byte[] data;
                            using (Stream inputStream = file.InputStream)
                            {
                                MemoryStream memoryStream = inputStream as MemoryStream;
                                if (memoryStream == null)
                                {
                                    memoryStream = new MemoryStream();
                                    inputStream.CopyTo(memoryStream);
                                }
                                data = memoryStream.ToArray();
                                File.WriteAllBytes(Constants.ImageFolderPath + imageid + ".jpg", (byte[])data);
                                //club.club_image = Convert.ToBase64String(data);
                            }
                        }
                    }
                }
                else
                {

                }

                //file.SaveAs(context.Server.MapPath(filePath + file.FileName));
                context.Response.Write("File uploaded");
            }
        }
    }

    public bool IsReusable
    {
        get
        {
            return false;
        }
    }
}

Solution 5

$(document).ready(function(){
   var status = $('#status');

        $('#frmUpload').ajaxForm({
            beforeSend: function () {
                if ($("#file").val() != "") {                   
                    $("#progressDiv").show();                    
                }
                status.empty();
            },
            success: function () {
                showTemplateManager();
            },
            complete: function (xhr) {
                if ($("#file").val() != "") {
                    var millisecondsToWait = 500;
                    setTimeout(function () {                       
                     $("#progressDiv").hide();
                    }, millisecondsToWait);
                }
                status.html(xhr.responseText);
            }
        });
});
Share:
60,981
user1400290
Author by

user1400290

Updated on August 25, 2020

Comments

  • user1400290
    user1400290 over 3 years

    I am developing a website in MVC 4, where user fill some information and save it to upload. all the information except image is being saved on server using Javascript, Json and Ajax, like given below:

    $.ajax({
                        url: action,
                        type: "POST",
                        data: JSON.stringify(PostViewModel),
                        dataType: "json",
                        contentType: "application/json; charset=utf-8",
                        beforeSend: function () {            
                        },
                        success: function (data) {
                        try{
                            alert('success');
                        }catch(err){alert(' Error: '+err);}
    
                        },
                        complete: function () {
                        },
                        error: function (xhr, ajaxOptions, thrownError) {
                            alert("Error occured");
                        }
                });
    

    But Now I need to upload his image also, but I couldn't find any method that can work with this approach or any without post back.

    I know putting FileUpload Control in Form tag and on press of submit button i can get image file like as given below:

     HttpPostedFileBase photo = Request.Files["photo"];
            if (photo != null)
            {
                Session["ImgPath"] = "~/Content/PostImages/" + photo.FileName;
                string path = Server.MapPath("~/Content/PostImages/");
                photo.SaveAs(path + photo.FileName);
            }
    

    But for this method I'll have to change my approach of saving content (using Javascript, Json & Ajax) which I can't.

    Please help

    Thanks.

  • Tareq
    Tareq about 10 years
    Thank you for posting this!
  • Sandip Bantawa
    Sandip Bantawa over 9 years
    Came over to the post today, everything was okay but UploadProgress has a jquery which kind add a bit bitterness on javascript :-)
  • vaibhav shah
    vaibhav shah almost 9 years
    What parameter should be passed to controller action ?
  • Vignesh Subramanian
    Vignesh Subramanian over 8 years
    should i use @if (System.Web.HttpContext.Current.Request.Files.AllKeys.Any()) { var pic = System.Web.HttpContext.Current.Request.Files["HelpSectionIma‌​ges"]; pic.SaveAs("/" + pic.FileName); } ?
  • tomalone
    tomalone over 6 years
    I'm thinking - why is Ajax.BeginForm not working here, but pure JS ist :) Still - nice answer
  • Max Farsikov
    Max Farsikov over 5 years
    Please add some explanation