Using uploadify in ASP.Net MVC application


Dropbox is getting more and more popular. I use it on my desktop, laptop, iphone, and ipad. Once I went to a post office to post a document, and realised that I don't know the address. I had my iphone with me, so used Dropbox to get the address. It was so useful, and ever since, I became a fan of Dropbox.

Anyway, Dropbox has nice Flash-based upload functionality, and I wanted to mimic the feature in my asp.net application. SlickUpload is a very good component, but commercial. I googled and came across uploadify.

The site has good example code and a link to asp.net example too. If you want to make your file upload testable, read Scott hanselman's fantastic post about it.

The below is my code. One thing to note in the code are

[sourcecode language="csharp"]
public ActionResult UploadFiles()
{
foreach (string file in Request.Files)
{
var postedFileBase = Request.Files[file];
if (postedFileBase.ContentLength == 0)
continue;

string savedFilename = Path.Combine(AppDomain.CurrentDomain.BaseDirectory,
Path.GetFileName(postedFileBase.FileName));
postedFileBase.SaveAs(savedFilename);
}

return View();
}

[/sourcecode]

[sourcecode language="javascript"]
$(function(){
$("#file").uploadify({
'uploader': '<%= Url.SiteRoot() %>/public/images/uploadify.swf',
'script': 'Home/UploadFiles',
'cancelImg': '<%= Url.SiteRoot() %>/public/images/cancel.png',
'auto': false,
'multi': false
});
})

<h2>Simple file upload.</h2>
<p>

<form action="<%= Url.Action("UploadFiles", "Home") %>" method="post" enctype="multipart/form-data">

<p>
<input type="file" name="file" id="file" />
<a href="javascript:$('#file').uploadifyUpload();">Upload Files</a>
</p>

</form>
</p>

[/sourcecode]