Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to upload file via ajax

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);
        }
like image 655
Jobert Enamno Avatar asked Oct 21 '22 11:10

Jobert Enamno


1 Answers

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.

like image 104
Darin Dimitrov Avatar answered Oct 27 '22 09:10

Darin Dimitrov