Tuesday, May 26, 2009

Using jQuery Plugin Uploadify with Asp.net MVC

Just started using this great jQuery plugin called Uploadify, that lets you upload multiple files to the server. It uses flash to queue the files and send them one by one to the server. Plus provides feedback and all other types of goodies. The implementation is pretty straight foward.

Just add this client side code.

<script type="text/javascript" src="/Content/js/jquery-1.3.2.min.js"></script>
<script type="text/javascript" src="/Content/js/jquery.uploadify.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$("#fileInput").uploadify({
uploader: "/Content/swf/uploadify.swf",
script: "/UIImageViewer/Upload",
cancelImg: "/Content/imgs/cancel.png",
auto: true,
folder: "/uploads",
onError: function (a, b, c, d) {
if (d.status == 404)
alert("Could not find upload script. Use a path relative to: "+"<?= getcwd() ?>");
else if (d.type === "HTTP")
alert("error "+d.type+": "+d.status);
else if (d.type ==="File Size")
alert(c.name+" "+d.type+" Limit: "+Math.round(d.sizeLimit/1024)+"KB");
else
alert("error "+d.type+": "+d.text);
}
});
});
</script>
<body>
<input type="file" name="fileInput" id="fileInput" />
</body>


Then create a controller with a "Upload" action.
  public string Upload(HttpPostedFileBase FileData)
{
/*
*
* Do something with the FileData
*
*/
return "Upload OK!";
}


The tricky part, which drove me crazy, is that you need to use the "HttpPostedFileBase" class NOT the "HttpPostedFile" class. If you use the other class the script will return a "IO Error #2038" error message.