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