Upload Files In RAZOR With jQuery Uploadify Plugin

by prashant 17. March 2011 01:35

A Few months back I wrote a post on how to use jQuery plugin Uploadify to upload single/multiple files without postback in ASP.NET. Now a few days back I was working on a demo project which is on MVC 3 Razor and I use the same plugin without any problems. But the files that are being uploaded are uploaded to the root folder instead of the folder I specified to upload the files. After a lot of head scratching, I was unable to find the actual problem as why the file was not being uploaded to the folder of my choice. The answer was hidden in the normal file upload code that I saw in a forum posted by a user. So I gave it a try and it WORKED!! I was about to blog about the usage of uploadify plugin, but before that one of my blog reader asked me a question about uploading the files in Razor, though it was a bit different but this way it is pretty.

How do I do it?

Using the uploadify plugin in MVC 3 is the same as used with web forms, the only difference is that on the server-side we are going to use Controller and not a ASP.NET handler. Client side script is the same and there are only changes in script and folder parameter. Set the multi parameter to true if you wish to upload multiple files. 

<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': true,
            'auto': true
        });
    }
);
</script>

The script tag specifies the method in the Home Controller which handles the file upload. The Upload method in the Home Controller:

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

Now you can use the uploadify plugin with MVC 3 Razor and upload files in a more effective and efficient way and that too with no postback.

Download: FileUploader.zip (572.92 kb)

If you enjoyed this post, make sure you subscribe to my RSS feed!

Tags: , ,

ASP.NET MVC | Jquery

Comments (43) -

witiokz
witiokz United States
3/20/2011 10:04:05 AM #

I don't think, that using flash only uploaders in html5 world is a good idea ...

Reply

Raz
Raz United Kingdom
5/17/2011 10:43:47 AM #

Can you post  the mvc solution please.
I'm having trouble converting your previous example ASP to MVC

Thanks

Reply

Prashant
Prashant India
5/17/2011 7:42:32 PM #

Source code uploaded.

Reply

Raz
Raz United Kingdom
5/18/2011 11:28:22 PM #

Thanks

Reply

Nihal Singh
Nihal Singh India
6/9/2011 8:56:30 PM #

Hi Prashant,

Nice code. But it uploads only one file at a time. Can you provide the code for uploading multiple file? Like I will select files one by one and after clicking on upload files button it will upload all the files at once.

Thanks,
Nihal

Reply

prashant
prashant India
6/10/2011 7:41:54 AM #

@ Nihal: You need to set the multi property to true in the script. This will let you select multiple files and on submit button click it will upload all the selected files to the destination folder set by you.

Let me know if you still face any problem on this.

Reply

P&#233;tur
Pétur Iceland
7/6/2011 2:23:58 PM #

What is this    'script': 'Home/Upload'   ?  In the javascript.

Reply

prashant
prashant India
7/6/2011 7:20:18 PM #

@Pétur: The 'script' tag in the javascript is to specify the upload script for the uploadiy plugin. If you are using it with ASP.NET webforms then there is a generic handler like (upload.ashx) which handles the file upload whereas in MVC 'Upload' is the method inside Home controller to upload files.

In short script tag will have the name of the method, httphandler or the name of the method inside controller in MVC which is used to upload files (as shown in the above example). Please note that the actual upload of the file is done at the server side.

Reply

P&#233;tur
Pétur Iceland
7/7/2011 5:18:37 AM #

Ok. Now I am doing exactly the same thing (or that´s what I think Smile as you do. But I am doing it in a controller that is called MapController. But it doesn´t work and I think this might be the problem. Isn´t it correct that I should then have 'script': 'Map/Upload' ?

Reply

prashant
prashant India
7/7/2011 8:41:13 AM #

What error did you received? Try downloading the sample application from the post and then check if you are doing something wrong.

Reply

P&#233;tur
Pétur Iceland
7/8/2011 8:05:18 AM #

I did download the sample and it seems to work if I keep the Upload function in HomeController. But when I move it to other controller, it stop working.

This is the error I get when I try to upload a picture:
http://www.flickr.com/photos/27080355@N07/5912946032/

Reply

P&#233;tur
Pétur Iceland
7/8/2011 8:32:42 AM #

Here is the error: http://www.flickr.com/photos/27080355@N07/5912946032/

It works when I keep the Upload fnuction in HomeController. But now I am working in another controller and it stops working.

Any idea what might be wrong?

Reply

prashant
prashant India
7/8/2011 8:54:03 AM #

I added a new controller named MapController and then change script tag as: Map/Upload and it is working for me. See below script I am using
<script type="text/javascript">
    $(window).load(
    function () {
        $("#fileuploader").fileUpload({
            'uploader': '/Scripts/uploader.swf',
            'cancelImg': '/Images/cancel.png',
            'buttonText': 'Select Image',
            'script': 'Map/Upload',
            'folder': '/uploads',
            'fileDesc': 'Image Files',
            'fileExt': '*.jpg;*.jpeg;*.gif;*.png',
            'multi': true,
            'auto': true
        });
    }
);
    </script>

Reply

Michele DuBose
Michele DuBose United States
9/22/2011 6:08:53 AM #

What are the script files that should be added?

Reply

P&#233;tur
Pétur Iceland
7/8/2011 9:30:07 AM #

Ah ok then I must be doing something else wrong. Sry about the double post, I thought the first one didn't appear :p

Thx for the info, keep up a great blog site.

Reply

igor35
igor35 Slovenia
7/12/2011 3:43:26 PM #

Hi prashant,

I have the same problem like Nihal Singh, how to upload all the files at once. Now uploads only one file at a time Frown
Where in the script I can set the multi property to true ?

Thanks
Igor35

Reply

prashant
prashant India
7/12/2011 7:02:48 PM #

If you have selected "multi" tag then you can select multiple files from the dialog box. If you want to upload the files then create a button and then on the click of the button you can call the uploadify() method to upload all the selected file. It will be good if you check the official tutorial here.
http://www.uploadify.com/demos/

Reply

iamninyo
iamninyo Republic of the Philippines
7/15/2011 7:11:25 AM #

how can i use this uploadify in submit form, i mean after i browse images then i thats the time i will hit the submit button to finally save the images i selected??? any help???


thanks thanks

Reply

prashant
prashant India
7/16/2011 8:35:54 AM #

To do that you need to add the below script on the click of the button.
javascriptEmbarassed('#fileuploader').uploadifyUpload()

You can check the demo at the official website here: http://www.uploadify.com/demos/

Reply

Alireza
Alireza Iran
7/16/2011 10:51:33 PM #

I have a problem . When I upload a file, after a second it gives me IO Error!
What should I have done?!

Reply

Sanjay
Sanjay India
8/7/2011 10:46:33 PM #

Hi Prashant,

I need to know whether we can have a preview of an image file as a thumbnail that has been selected by the plugin and then on clicking another button upload it to the server.

Reply

prashant
prashant India
8/9/2011 6:29:10 PM #

Hi Sanjay,

Yes, you can do that also. You can use jquery to do that of you can modify the script in the plugin to do that.

I like this approach by the way. Smile

Reply

paige
paige South Africa
8/16/2011 12:37:26 AM #

Hey Prashant
I need to know, how do you integrate your solution with a grid...   i have a grid and i need to upload document in each row of the grid and display it.. in your code you have this line ..
  'buttonText': 'Select Image', and is the one that the user click on to upload the document.
how do you do it when using grid and you have a image-button for user to click?
//This is the area that has the install
<label  id="lblDocunam"> documentxyz.doc</label >
                        <a href="@Url.Action("AttachLetter", new { sid = @item.ClientId })" >
                            <img class="attachGrid" alt="" />
                        </a>
I thank you in advance for help....

Reply

Jay
Jay India
8/24/2011 2:21:06 AM #

Hey Prashant ..

really Nice blog..

Have one question ..  how will i return something from controller from Upload action?  As your code returning "OK"  from controler side. I want it back in JS as want to manipulate somethin ...

Thnks in advance.

Reply

Khash
Khash Australia
9/20/2011 3:52:52 PM #

Hi there,
Thanks for you help , I'm trying to use the plugin and I recieve the IO Error each time . It happens befor the data has been sent to the Action and after the progress bar completed.

could you please help

Reply

Khash
Khash Australia
9/20/2011 4:23:35 PM #

Hi there again,
I put an onError Event and caouth the errors, it says : IO Error : Undefined and HTTP Eroor : Undefined

Reply

prashant
prashant India
9/22/2011 7:45:11 AM #

@Khash: try checking the path in the script.

Reply

Michele DuBose
Michele DuBose United States
9/22/2011 7:50:51 AM #

What are the script files that should be added?

Reply

Prashant
Prashant India
9/22/2011 7:54:31 AM #

@Michele: Download the files above in the post you will find the files added in the above code. It only contains the files used by the uploadify plugin i.e. the style.css, uploadify.js plugin file and other mandatory images to run the plugin.

Reply

Eldar
Eldar United States
9/24/2011 10:50:25 PM #

if you put the  file uploader at a location other then root it wont work and stuck on uploading

seems it works only at the root page (the file upload can be at diffrent location BUT the file uplodaer script must be at root.. )

tried to change pathname at the script but still its not working...

Reply

Mr Duc
Mr Duc Vietnam
11/9/2011 6:35:27 PM #

Hi prashant , Why  it is only working in view index, but other view is not working, Please guide for me, thank

Reply

Mr Duc
Mr Duc Vietnam
11/9/2011 8:01:49 PM #

I think it is only working in router default

Reply

tungsoti
tungsoti Vietnam
11/11/2011 3:08:00 PM #

i have the same problem with Mr Duc

Reply

Sanjaikanth
Sanjaikanth India
11/15/2011 4:00:44 AM #

Prashant,
When i tried t upload manually it shows error(i am using MVC project)
<a onclick="javascriptEmbarassed('#fileuploader').uploadify();">Upload Files</a>
it says property does not exists.
How to upload manually?

Reply

Prashant
Prashant India
11/15/2011 5:15:35 AM #

@Sanjaikanth: You are missing a jquery Uploadify javascript file. Cross-check every file that needs to be included.

Reply

Sanjaikanth
Sanjaikanth India
11/15/2011 8:42:14 PM #

Prashant,
Thanks for your relpy.
I am using  $("#fileuploader").fileUpload() method in the sample MVC Razor  application that is available in this site.
and i am trying to invoke using <a onclick="javascriptEmbarassed('#fileuploader').uploadify();">Upload Files</a>
i make 'auto': false, I need to send file when i click "Send" button in my application.
jquery.uploadify.j is available in the solution.
Any help?
Thanks,
Sanjaikanth.

Reply

Jay
Jay United States
11/25/2011 10:57:54 AM #

Great article. One comment in terms of best practice, I would stay away from flash. (compatibility and security issue.) I would recommend to use a non-flash jquery file upload solution.  Of course, it is a matter of choice.

Reply

Raghu
Raghu United States
12/6/2011 9:05:56 PM #

Is adobe flash needed to run this . Because the script contains swf file ?

Reply

Prashant
Prashant India
12/7/2011 12:31:55 AM #

Yes, but only the flash player plugin for the browser not the complete Adobe Flash suite.

Reply

amir
amir United States
1/27/2012 3:25:17 AM #

hi, I just your razor sample it is working fine with 1.4 though I've 1.5 jquery files. Currently I added jquery.uploadify.js and upload.swf to the script forlder and also uploadify.css to the Content folder.. and the cancel image. But when I run my app i get "$" not defined js error.

can you help me out what did i miss there. also what If i don't want auto func. rather i want to submit it on some button click what will be the way to go about it. thanks in adnvace.

Reply

Prashant
Prashant India
1/27/2012 8:52:26 AM #

Download the latest uploadify plugin and then try or there is a possibility that the jquery file has not been referenced/loaded correctly.

By auto func. you mean to disable auto upload and want to upload files on the button click?

Reply

Joe Reynolds
Joe Reynolds United States
2/22/2012 7:07:31 AM #

I downloaded and installed the mvc project. It compils and runs.

When I select multiple images it just automatically uploads the images to the uploads directory after the select is complete. There is no chance to remove or add to the list and no Submit button to do the upload.

Reply

Prashant
Prashant India
2/22/2012 8:51:23 AM #

To disable the auto upload set the uploadify plugin property to false as shown below:
'auto': false

Now as you have set the auto property to false you need to upload the file on the click of the button. I am not sure with the version I have used as there is an updated version available now for Uploadify plugin. Therefore I recommend you to check the latest release at the official site.

On the click of the button (if you have upgraded the plugin version), then you need to something like this:
$('#file_upload').uploadifyUpload();

Reply

Pingbacks and trackbacks (8)+

Add comment




  Country flag
biuquote
  • Comment
  • Preview
Loading


Visit blogadda.com to discover Indian blogs Computers Blogs

About Me

Name of authorPrashant Khandelwal.
Programmer and tech enthusiast. More...

Feeds Subscribe Twitter Facebook Google Plus Linked In Delicious

My Visual Studio Achievements

Badges

MVB

MVP Blog Badge.

HTML5 Powered with CSS3 / Styling, Graphics, 3D & Effects, Multimedia, Performance & Integration, Semantics, and Offline & Storage

Month List

Blog Stats

344,739 Hits

Adverts

Disclaimer

The opinions expressed herein are my own personal opinions and do not represent my employer's view in anyway.

© Copyright 2012

Creative Commons License