Tuesday, March 1, 2011

Ajax file upload

Hi, I have a form that upload a file, I would process the file inline with ajax but I don't know how I can get the data with ajax.

In my script I use this method:

 $.ajax(
            {
                type:    "POST",
                url:     "upload.php",
                data:    ({ file : '???' }),
                success: function(msg)
                {
                    $('#upload_box').html(msg);
                }
            });

How I can declare the 'file' var fetching the file data? (filename, tmp_name, type, size, etc).

From stackoverflow
  • You can't do this with a standard AJAX request. The most common workaround is to post the file to a hidden iFrame as seen in this tutorial.

    Since you are using jQuery, you may find the AJAX Upload library useful.

  • You could upload the file to the server, call a php script to read it back to you and then dump it into whatever tag you wanted to read from

       //In your onUpload callback
       var req = createRequest();
       req.open("GET", 'upload.php?file=' + filename,true);
    
       req.send(null);
       //Do your status checking
       var filetext= req.responseText;
    

    Frameworks don't solve all problems, and if you are using one that requires work arounds, you should return to basics, because this CAN be done using vanilla javascript with some PHP.

    Adam Lassek : It's not the framework that needs to be worked around, but basic HTML behavior. You can't currently do file uploads in XHR.
    MikeEL : XHR (XMLHTTPRequest) is not HTML behavior. Its Javascript. I do file creation on the fly using javascript and php, and I read the file back out for all of my comments, and this is much the same, only you need to wait for the file to be moved from the temp area, to the final area on the server. If you would like more information on this, ask a question and let me know where it is, and I'll post some code for you.
    Adam Lassek : Should have said Http behavior. In fact, it's a bit lower-level than javascript. Most browsers provide an API through js but IE 5-6 implemented it as an ActiveX object instead. My point was this is not a js framework issue.
  • I've solved with the Jquery Form Plugin (http://malsup.com/jquery/form/)

0 comments:

Post a Comment