Reputation: 4461
I have file upload which doesn't use form to upload the file instead I want to upload it using ajax. I tried the following approach but I cannot pass the file. It's null. Please help. Below is my implementation.
HTML and jQuery function
<div id="Upload">
<input type="file" accept="application/x-shockwave-flash" id="virtualtourfile" enctype="multipart/form-data"/>
<input type="button" value="Upload" id="btnUpload"/>
</div>
$('#btnUpload').click(function () {
$.ajax({
url: "uploadvideo",
type:'POST',
data: $("#virtualtourfile:file"),
success: function (data) {
}
});
});
Controller
public ActionResult UploadVideo(HttpPostedFileBase file)
{
return Json("", JsonRequestBehavior.AllowGet);
}
Upvotes: 5
Views: 6646
Reputation: 4010
I've used a few plugins and I found the Kendo UI upload plugin nice, here is a link how it works:
http://demos.kendoui.com/web/upload/async.html
and you can find the sample project for Asp.Net MVC 3 here: http://www.kendoui.com/forums/ui/upload/upoad-with-mvc.aspx
[HttpPost]
public ActionResult Save(IEnumerable<HttpPostedFileBase> attachments)
{
// The Name of the Upload component is "attachments"
foreach (var file in attachments)
{
// Some browsers send file names with full path. This needs to be stripped.
var fileName = Path.GetFileName(file.FileName);
var physicalPath = Path.Combine(Server.MapPath("~/App_Data"), fileName);
file.SaveAs(physicalPath);
}
// Return an empty string to signify success
return Content("");
}
Upvotes: 1
Reputation: 1039398
There are a couple of options. If the client browser supports the HTML5 File API
you could use it to upload a file asynchronously to the server. If you need to support legacy browsers that do not support this API you could use a file upload component such as Uploadify
, Fine uploader
, jquery form
, ... The advantage of those plugins is that they will test the capabilities of the browser and if it supports the File API it will use it, otherwise it will fallback to older techniques such as hidden iframes or Flash movies.
Upvotes: 2