user2031327
user2031327

Reputation:

using modal box for file upload

In my MVC application am allowing the user to upload a file. Whenever user clicks on upload file link this is the link

  <a class="upload" onclick="upload(this);">

the file upload should get open in modal box.

function upload(box) {
       var box = dhtmlx.modalbox({
           title: "Upload File",
           text: "<div id='form_in_box'><div>Choose a PDF file to upload <hr/><label>Enter the URL <input type='file' name='file' id='file' style='width: 400px; height: 27px;'></label><br></div><div><span class='dhtmlx_button'><input type='submit' value='Upload File' style='width: 86px' onclick='save_file(this)'></span><span class='dhtmlx_button'><input type='button' value='Cancel' onclick='close_file(this)' style='width:80px;'></span></label></div></div>",
           width: "300px"
       });
   }
   function close_file(box) {

       dhtmlx.modalbox.hide(box);

   }

   function save_file(box) {
       var file = $("#file").val();
       if (file == "") {
           alert("Enter the URL");
           return false;

       dhtmlx.modalbox.hide(box);
       dhtmlx.message("Uploading the file");
       $.post("/FileUpload/Upload",
       { file: '' + file + '' });
   }
  and the controller code is 
[HttpPost]
    public ActionResult Upload(HttpPostedFileBase file)
    {
        SaveFile(file);
        return RedirectToAction("Index");
    }

but the problem is am getting error i.e. file = null

Upvotes: 0

Views: 1174

Answers (1)

Darin Dimitrov
Darin Dimitrov

Reputation: 1039130

You cannot upload files using an AJAX request ($.post). If your browser supports the HTML5 File API you could use the new XHR2 object. If not, you could use a file upload plugin such as Uploadify, Fine Uploader or PLUpload. All those plugins will detect whether the client browser supports the HTML5 File API and use it if so and if it doesn't they will fallback to standard techniques such as using hidden iframes or Flash movies. The advantage of using one of them is that you don't need to be coding for all the possible cases.

Here's an example of how you could upload the file using the HTML5 File API:

function save_file(box) {
    var file = document.getElementById('file');
    if (file.value == '') {
        alert('Enter the URL');
        return false;
    }

    dhtmlx.modalbox.hide(box);
    dhtmlx.message('Uploading the file');

    var fd = new FormData();
    fd.append('file', file.files[0]);
    var xhr = new XMLHttpRequest();
    xhr.open('POST', '/FileUpload/Upload', true);
    xhr.onreadystatechange = function () {
        if (xhr.readyState == 4 && xhr.status == 200) {
            alert('file successfully uploaded to the server');
        }
    };
    xhr.send(fd);
}

Upvotes: 1

Related Questions