Upload Files In RAZOR With jQuery Uploadify Plugin

by prashant 16. March 2011 16: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. The program works similarly to simple file upload sites in its ease of use. 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)

Comments (62)

C&#233;dric GALOU
Cédric GALOU
9/6/2012 7:10:03 PM #

Home is the name of the contoller ans Upload is the method in the controller for the upload.

Sroush
Sroush
7/31/2012 8:51:33 PM #

Parshant, This is a great tutorial however, I want to be able to show the upload progress while I do NOT want to use FLASH at all... can I do that? I do not want it to be associated with any kind of flash... Please advice. Thanks

Prashant
Prashant
7/31/2012 9:36:17 PM #

It is possible, but for that you need to play around with the plugin code. This will be a tedious work. You can try some other jquery plugins to upload files. Try this: http://www.jainaewen.com/files/javascript/jquery/iframe-post-form.html

manivannan
manivannan
7/19/2012 2:20:13 AM #

It is availble in both free and commercial version? Can i use this free version for commercial version? becuase my customer doesnt want to any of the plugin(third party) plugin unless license purchase....

Prashant
Prashant
7/19/2012 10:34:57 AM #

The license used for Uploadify is MIT License, which is an Open-Source License. There are two versions of the Uploadify, I have used the free one which is flash based and the paid one is HTML5 version which, if you wish to use then you need to purchase. Read more on this here: http://www.uploadify.com/download/

Umair
Umair
6/18/2012 5:22:37 PM #

I have an issue when i use this code. error show : IO Error can you people help me about this error. here is my code: [b]JS:[/b] [i]$(window).load( function() { $("#fileuploader").fileUpload({ 'uploader': '/Scripts/uploader.swf', 'cancelImg': '/images/cancel.png', 'buttonText': 'Select Image', 'script': 'ShowClientQuotation/Upload', 'folder': '/images', 'fileDesc': 'Image Files', 'fileExt': '*.jpg;*.jpeg;*.gif;*.png', 'multi': true, 'auto': true }); } );[/i] [b]html:[/b] [i]<div id="fileuploader"></div>[/i] My Controller Name: [quote]ShowClientQuotation[/quote] [i] public string Upload(HttpPostedFileBase fileData) { var fileName = this.Server.MapPath("~/images/UserProfilePic/" + System.IO.Path.GetFileName(fileData.FileName)); fileData.SaveAs(fileName); return "ok"; }[/i]

Umair
Umair
6/18/2012 5:51:06 PM #

i have face an error please visit this url to solve my error: http://stackoverflow.com/questions/11082444/error-in-uploading-image-through-jquery-asp-net-mvc-3-0 thankyou in advance.

Prashant
Prashant
5/23/2012 8:13:50 PM #

Thanks!! 1. To set the maximum size of the file use the [b]fileSizeLimit[/b] option of the plugin. Read more here on the plugin official site: http://www.uploadify.com/documentation/uploadify/filesizelimit/ 2. To set the customize location you need to use the ViewBag property of MVC3 and then set the location for the sign in user from the controller method. 3. To check whether the file exists from before with the same name or not then you need to call a controller method which check whether the file exists or not. The controller method will be called just like the upload method in the above script. In the official documentation they have accomplish it by using a PHP script. Let me know if this solves your problem or not.

manish
manish
5/20/2012 1:39:08 PM #

Hi Prashant, Thanks for nice article. i am working on MVC project. I have few questions, 1) How to set the maximum size of the file 2) Customise (dynamic) location of the folder (different-2 folder for different-2 user). 3) File Exts check Thanks Manish

Conrad Delenia
Conrad Delenia
4/2/2012 5:27:33 AM #

I had the same problem and solved it by rooting the script parameter 'script': '/Home/Upload'. I moved the Upload action to a different controller: FileController, moved the upload folder to a network share, and moved the jQuery function to the shared master view _Layout.cshtml. This allowed me to put the upload button on any view. This works in debug, but when I published it to my web server, the upload button fails to display. Here is my function: $("#fileuploader").fileUpload({ 'uploader': '@Url.Content("/Scripts/uploader.swf")', 'cancelImg': '/Images/cancel.png', 'buttonText': 'Select Image', 'script': '/File/Upload', 'folder': '//localhost/uploads', 'fileDesc': 'Image Files', 'fileExt': '*.jpg;*.jpeg;*.gif;*.png;*.txt;*.kml;*.kmz', 'multi': true, 'auto': true }); Any suggestions as to why it does not work when it is published?

asdasd xdcvssd
asdasd xdcvssd
3/29/2012 6:08:19 AM #

It doesn't work under Safari and Firefox

Prashant
Prashant
3/29/2012 6:36:50 PM #

The version I used in the example above is using the old version of uploadify plugin. Download the new version of the plugin and then try it. Good Luck!!

Prashant
Prashant
3/29/2012 6:42:37 PM #

CHMOD? Are you using LINUX server? If yes, then I doubt that it will work as I have used an ASP.NET handler which will work only in windows environment. If you are in LINUX then go to the Uploadify official website where you can find examples in PHP which will work perfectly for you in LINUX.

Mohammad Sharaf Ali
Mohammad Sharaf Ali
3/27/2012 9:29:21 PM #

I cant upload the file to the specified folder in the uploadify script. Im using 000webhost service and in public_html I have a folder named uploading but after uploading files using uploadify my uploading folder is always empty. Below is my script: Please help me asap and I have set 777 in chmod for uploading folder plus all rights read write. <script type="text/javascript"> $(window).load( function () { $("#fileuploader").fileUpload({ 'uploader': '/Scripts/uploader.swf', 'cancelImg': '/Images/cancel.png', 'buttonText': 'Select Image', 'script': 'Map/Upload', 'folder': '/uploading', 'fileDesc': 'Image Files', 'fileExt': '*.jpg;*.jpeg;*.gif;*.png', 'multi': true, 'auto': true }); } ); </script>

Prashant
Prashant
3/24/2012 11:52:28 AM #

Have you made any changes in the application after download? The problem you stated above could be because of the miss-match in the jquery version. Try downloading the latest Uploadify plugin version and then try.

shailesh
shailesh
3/23/2012 7:29:14 PM #

Hi Prashant Why it is only working in view index, but other view is not working, Please guide for me, thank. Please.... Mr Duc Vietnam Hi prashant , Why it is only working in view index, but other view is not working, Please guide for me, thank tungsoti Vietnam i have the same problem with Mr Duc I think it is only working in router default

torontom
torontom
3/23/2012 11:57:36 PM #

build without error, but cannot run the application after download the error I got happens in jquery.uploadify.js -> flashVer=version.replace("WIN ","").replace(",",".") the message is: Microsoft JScript runtime error: Unable to get value of the property 'replace': object is null or undefined How can I fix this? I did not make any change after download and unzip

Prashant
Prashant
3/18/2012 12:01:37 PM #

Thanks... I haven't done this but initially I though to do this, so I have an idea on how you can do this. First, make sure that the files that are being uploaded by the users should be saved in the folder and with one entry in the database with the name of the image, path of the image and the user id/name. Now when the user logs beck in, list out all the records associated with that particular user and show it to the user. The images will be saved in the physical location on the server, here you need to get the path of the uploaded image and then the logged in user id or name and save it to the database. This is the best approach I have in my mind. Let me know if you have any other ideas.

hacknop
hacknop
3/14/2012 8:35:31 PM #

Hi Prashant, First off, thanks for ur very clean and concise post on the upload plugin for mvc. I was wondering how i can add functionality to allow users to log back into the site and download those files that they saved earlier or for an administrator to get a list of all files in a particular folder any help is much appreciated~~

Joe Reynolds
Joe Reynolds
2/21/2012 10:07:31 PM #

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.

Prashant
Prashant
2/21/2012 11:51:23 PM #

To disable the auto upload set the uploadify plugin property to false as shown below: [b]'auto': false[/b] 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: [b]$('#file_upload').uploadifyUpload();[/b]

amir
amir
1/26/2012 6:25:17 PM #

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.

Prashant
Prashant
1/26/2012 11:52:26 PM #

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?

Raghu
Raghu
12/6/2011 12:05:56 PM #

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

Prashant
Prashant
12/6/2011 3:31:55 PM #

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

Jay
Jay
11/25/2011 1: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.

Sanjaikanth
Sanjaikanth
11/15/2011 11:42:14 AM #

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="javascript:$('#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.

Sanjaikanth
Sanjaikanth
11/14/2011 7:00:44 PM #

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

Prashant
Prashant
11/14/2011 8:15:35 PM #

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

tungsoti
tungsoti
11/11/2011 6:08:00 AM #

i have the same problem with Mr Duc

Mr Duc
Mr Duc
11/9/2011 9:35:27 AM #

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

Mr Duc
Mr Duc
11/9/2011 11:01:49 AM #

I think it is only working in router default

Eldar
Eldar
9/24/2011 1: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...

Michele DuBose
Michele DuBose
9/21/2011 9:08:53 PM #

What are the script files that should be added?

prashant
prashant
9/21/2011 10:45:11 PM #

@Khash: try checking the path in the script.

Michele DuBose
Michele DuBose
9/21/2011 10:50:51 PM #

What are the script files that should be added?

Prashant
Prashant
9/21/2011 10:54:31 PM #

@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.

Khash
Khash
9/20/2011 6:52:52 AM #

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

Khash
Khash
9/20/2011 7:23:35 AM #

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

Jay
Jay
8/23/2011 5:21:06 PM #

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.

paige
paige
8/15/2011 3:37:26 PM #

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 .. [quote] 'buttonText': 'Select Image',[/quote] 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....

prashant
prashant
8/9/2011 9:29:10 AM #

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. :)

Sanjay
Sanjay
8/7/2011 1: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.

Alireza
Alireza
7/16/2011 1: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?!

prashant
prashant
7/15/2011 11:35:54 PM #

To do that you need to add the below script on the click of the button. javascript:$('#fileuploader').uploadifyUpload() You can check the demo at the official website here: http://www.uploadify.com/demos/

iamninyo
iamninyo
7/14/2011 10:11:25 PM #

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

igor35
igor35
7/12/2011 6:43:26 AM #

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 :( Where in the script I can set the multi property to true ? Thanks Igor35

prashant
prashant
7/12/2011 10:02:48 AM #

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/

P&#233;tur
Pétur
7/8/2011 12: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.

P&#233;tur
Pétur
7/7/2011 11:05:18 PM #

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/

P&#233;tur
Pétur
7/7/2011 11:32:42 PM #

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?

prashant
prashant
7/7/2011 11:54:03 PM #

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>

P&#233;tur
Pétur
7/6/2011 5:23:58 AM #

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

prashant
prashant
7/6/2011 10:20:18 AM #

@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.

P&#233;tur
Pétur
7/6/2011 8:18:37 PM #

Ok. Now I am doing exactly the same thing (or that´s what I think :) 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' ?

prashant
prashant
7/6/2011 11:41:13 PM #

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

Nihal Singh
Nihal Singh
6/9/2011 11:56:30 AM #

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

prashant
prashant
6/9/2011 10:41:54 PM #

@ Nihal: You need to set the [b]multi[/b] 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.

Raz
Raz
5/18/2011 2:28:22 PM #

Thanks

Raz
Raz
5/17/2011 1:43:47 AM #

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

Prashant
Prashant
5/17/2011 10:42:32 AM #

Source code uploaded.

witiokz
witiokz
3/20/2011 1:04:05 AM #

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

Add Comment

*
*
 

Visit blogadda.com to discover Indian blogs Computers Blogs