Upload and Show Image Without Post Back With Jquery

by prashant 11. October 2011 11:20

Previously in a lot of hurry I wrote a post on how to upload files in MVC3 with the help of Uploadify, a famous jQuery plugin to upload files. If you have not heard about it yet, then it is time for you to check and find out what this plugin can do for you. Appending my last post about this plugin (which was not very well written) I tried one more thing with it today. This time I am trying to upload an image and then show it inside a DIV without a post back. If you have the source code from the previous post, then it will be good as you need not to start from the scratch.

I assume that you are a good designer as I am not. I am saying this because I really got a blank head in designing. Therefore it is up to you how you are going to show off the images on the page, I am just telling you a way to do that. I am using MVC3 for this example but it will work for both web forms and MVC. The only difference in MVC and web forms is in the server side code which is responsible to upload the file. If you are using MVC3 then your method to upload the file in the controller will be something like this:

public string Upload(HttpPostedFileBase fileData)
{
        var fileName = this.Server.MapPath("~/uploads/" + System.IO.Path.GetFileName(fileData.FileName));
        fileData.SaveAs(fileName);
        return "OK";
}

As we are using Uploadify, we now have to make changes in some of the parameters of the plugin. The Upload method is inside home controller, so the script parameter of the plugin will be /Home/Upload. For my convenience I have changed the multi and auto parameter to false and true respectively. By now this is the jQuery code I have:

<script type="text/javascript">
$(window).load(
function () {
    $("#fileuploader").fileUpload({
        'uploader': '/Scripts/uploader.swf',
        'cancelImg': '/Images/cancel.png',
        'buttonText': 'Select Image',
        'script': 'Home/Upload',
        'folder': '/uploads',
        'fileDesc': 'Image Files',
        'fileExt': '*.jpg;*.jpeg;*.gif;*.png',
        'multi': false,
        'auto': true
    });
}
);
</script>

In the end I append one more parameter onComplete which gets fired when the plugin finish uploading the file. To get the uploaded path of the image I am using fileObj.filePath and response to check if the file has been uploaded successfully or not. If the response I received after the uploading of the file is completed is ok then I will set the html to show the image in another DIV. Below is the complete configuration of the plugin.

<script type="text/javascript">
$(window).load(
function () {
    $("#fileuploader").fileUpload({
        'uploader': '/Scripts/uploader.swf',
        'cancelImg': '/Images/cancel.png',
        'buttonText': 'Select Image',
        'script': 'Home/Upload',
        'folder': '/uploads',
        'fileDesc': 'Image Files',
        'fileExt': '*.jpg;*.jpeg;*.gif;*.png',
        'multi': false,
        'auto': true,
        'onComplete': function (event, ID, fileObj, response) {
            if (response == "OK") {
                $("#uImg").addClass("loading");
                var htmlString = "<img src=\"" + fileObj.filePath + "\" alt=\"" + fileObj.name + "\" />";
                $("#uImg").html(htmlString);
                $("#uImg").removeClass("loading");
            }
        }
    });
}
);
</script>

Just to demonstrate I have placed an alert message box with the response which got fired on the onComplete event after the image has been uploaded successfully. After this I have created a html string which is actually a html img tag with src and alt tags. I have then set the same html string to another DIV which acts as a holder of the image being uploaded. Here is an output after the image is uploaded. Just to remind you, it is all done without post back.

This is it, try it yourself and I recommend you to check out the documentation of the plugin I used. Check out the other links below and one more thing that I would like you to do is to set the multi property of the plugin to true and the try uploading multiple images. If you end up making something awesome then do share with me/us.

Related Links:

Comments (8)

Gregory Weiss
Gregory Weiss
10/26/2011 7:40:03 AM #

Hey there, First this is one of the BEST posts I've seen. I'm constantly sifting through post and after post just to find code and tutorials for what I need to do and most of them are way over complicated and dont really show anyone how to do something is a clear way. This is AWESOME. I have implemented this code and its working great, but I can't get the onComplete event to fire. I am trying to trace it but I can't even attach to the code after the uploads have completed. Also, when I download the Uploadify .zip file, they have a different JQuery script than you are using (jquery.uploadify.v2.1.4.js). When I try to execute this with the latest uploadify file, I get an error. Are you using the most recent scripts? Again, awesome awesome post. Any extra help is appreciated. Thanks!

Gregory Weiss
Gregory Weiss
10/26/2011 7:45:52 AM #

Forget it, I figured it out! :) Your original code has a return value of "ok" - lowercase. This revised code, the onComplete statement is looking for "OK" - upper case. It works, but I'd still like some feedback on the latest uploadify files vs what you are using. Thanks!

Gregory Weiss
Gregory Weiss
10/26/2011 8:11:09 AM #

Nevermind again, I see the differences between your script and the new files. Thanks!

prashant
prashant
10/26/2011 12:32:36 PM #

Thanks Gregory! I am using the old one. But there would not be any difference in implementation.

tungsoti
tungsoti
11/11/2011 8:07:33 AM #

in your example,if I delete method upload in home controller, it still work. but if it's not index view,the project doesn't work correct I don't understand about : 'script': 'Home/Upload', can't you help me

Jay
Jay
11/14/2011 12:43:40 PM #

It worked good in vs2010. When I deployed it to ii7, suddenly the upload button ( "Select File") button disapears. Any idea whay may cause this?

Prashant
Prashant
11/14/2011 8:17:39 PM #

@Jay: Are you sure that you havee uploaded all the necessary files like css and images...

Jay
Jay
11/26/2011 12:28:07 AM #

I published my web application using a web deploy.

Add Comment

*
*
 

Visit blogadda.com to discover Indian blogs Computers Blogs