dcsimg


DevX Home    Today's Headlines   Articles Archive   Tip Bank   Forums   

Results 1 to 4 of 4

Thread: upload file with ajax

  1. #1
    Join Date
    Nov 2009
    Posts
    4

    upload file with ajax

    Hi, I'm looking for a pure ajax (javascript) code for uploading a file to the server. This is, using an xhr (XMLHttpRequest) object and methods like (file).getAsBinary() and (xhr).sendAsBinary().

    At the same time, I need the php code for the script that is invoqued with the xhr.open() method, to access the uploaded file.

    If anyone can help me with this, I thank in advance very much.

  2. #2
    Join Date
    Apr 2007
    Location
    Sterling Heights, Michigan
    Posts
    8,663
    Welcome to DevX

    Does this help?

  3. #3
    Join Date
    Nov 2009
    Posts
    4
    Thank You!

  4. #4
    Join Date
    Nov 2009
    Posts
    4
    I found what I was looking for, so I post it for anyone who need it.

    The js file with main code included is:

    var Uploader = function(form, filefields) {

    /* **************************************************************************** *
    * Parametros del constructor: *
    * form: objeto formulario que contiene los campos input de tipo file con los *
    * archivos a hacer upload - no requerido *
    * filefields: array con objetos campos input de tipo file con los archivos a *
    * hacer upload - no requerido - si se pasa se toman en cuenta *
    * estos campos, si no se pasa se toman en cuenta los campos file *
    * del form (primer parametro) *
    * *************************************************************************** */

    this.form = form ;
    this.filefields = filefields ;
    };

    Uploader.prototype = {
    headers : {},

    /**
    * @return Array
    */
    get elements() {
    var fields = [];

    if (this.filefields != null) {
    fields = this.filefields ;
    } else {
    // gather INPUT elements
    var inputs = this.form.getElementsByTagName("INPUT");
    for (var l=inputs.length, i=0; i<l; i++) {
    fields.push(inputs[i]);
    }

    /* no incluyo campos select
    // gather SELECT elements
    var selects = this.form.getElementsByTagName("SELECT");
    for (var l=selects.length, i=0; i<l; i++) {
    fields.push(selects[i]);
    }
    */
    }

    return fields;
    },

    /**
    * @return String
    */
    generateBoundary : function() {
    return "---------------------------" + (new Date).getTime();
    },

    /**
    * @param Array elements
    * @param String boundary
    * @return String
    */
    buildMessage : function(elements, boundary) {
    var CRLF = "\r\n";
    var parts = [];

    elements.forEach(function(element, index, all) {
    var part = "";
    var type = "TEXT";

    if (element.nodeName.toUpperCase() === "INPUT") {
    type = element.getAttribute("type").toUpperCase();
    }

    if (type === "FILE" && element.files.length > 0) {
    var fieldName = element.name;
    var fileName = element.files[0].fileName;

    part += 'Content-Disposition: form-data; ';
    part += 'name="' + fieldName + '"; ';
    part += 'filename="'+ fileName + '"' + CRLF;

    part += "Content-Type: application/octet-stream" + CRLF + CRLF;
    part += element.files[0].getAsBinary() + CRLF;
    } else {
    part += 'Content-Disposition: form-data; ';
    part += 'name="' + element.name + '"' + CRLF + CRLF;

    part += element.value + CRLF;
    }

    parts.push(part);
    });

    var request = "--" + boundary + CRLF;
    request+= parts.join("--" + boundary + CRLF);
    request+= "--" + boundary + "--" + CRLF;

    return request;
    },

    /**
    * @return null
    */
    send : function(xhr) {
    var boundary = this.generateBoundary();

    xhr.onprogress = function(evt) {
    if (evt.lengthComputable) {
    evt.target.curLoad = evt.loaded;
    evt.target.log.parentNode.parentNode.previousSibling.textContent =
    Number(evt.loaded/k).toFixed() + "/"+ Number(evt.total/k).toFixed() + "kB";
    }
    if (evt.lengthComputable) {
    var loaded = (evt.loaded / evt.total);
    if (loaded < 1) {
    var newW = loaded * width;
    if (newW < 10) newW = 10;
    evt.target.log.style.width = newW + "px";
    }
    }
    };

    var contentType = "multipart/form-data; boundary=" + boundary;
    xhr.setRequestHeader("Content-Type", contentType);

    for (var header in this.headers) {
    xhr.setRequestHeader(header, headers[header]);
    }

    // finally send the request as binary data
    xhr.sendAsBinary(this.buildMessage(this.elements, boundary));
    }
    };


    The js functions included in the page that has the file control and the upload button is:

    function PreviewImagen() {

    /* ********************************************************** *
    * previsualiza imagen subida con upload() *
    * en div adm_producto_img *
    * ********************************************************** */


    var filefields = [];
    var form = document.getElementsByTagName("form")[0] ;
    filefields.push(document.getElementById("img_file")) ;
    var uploader = new Uploader(null, filefields);
    xhr.open("POST", "adm_producto_proc.php", true);
    xhr.onreadystatechange = callback ;

    document.getElementById('img_preview').disabled = true ;
    uploader.send(xhr);
    }

    function callback(){
    if (xhr.readyState == 4) {
    if (xhr.status == 200) { //El código 200 de HTTP en un test para una aplicacion, si es verdadero concluyo correctamente
    // respuesta texto
    var dir = document.getElementById("adm_producto_img") ;
    dir.innerHTML = xhr.responseText ; // respuesta texto
    document.getElementById('img_preview').disabled = false ;
    }
    }
    }


    PreviewImagen() is a function called in the onClick of the Upload button.

    img_file is the id of the file control in the page.

    adm_producto_proc.php is the page that is called by the ajax xhr object, and the one that "receives" the uploaded file.

    the text that adm_producto_proc.php outputs is received by the callback() function in xhr.responseText.

    the code in adm_producto_proc.php can be this one:

    move_uploaded_file($_FILES["img_file"]["tmp_name"], "upload/" . $_FILES["img_file"]["name"]) ;
    echo "file uploaded ok" ;


    The bad news is that this only works in Firefox.
    Not in IE7/8, not in Google Chrome.

    If I find the modifications needed to work in theese I post it.

    Best regards


Similar Threads

  1. Replies: 0
    Last Post: 09-25-2006, 11:46 AM
  2. Replies: 0
    Last Post: 11-10-2005, 11:07 PM
  3. File upload help
    By Chris in forum ASP.NET
    Replies: 5
    Last Post: 09-01-2002, 07:46 AM
  4. How long before the next version??
    By _CAG in forum .NET
    Replies: 146
    Last Post: 08-12-2002, 10:40 PM
  5. NullPointerException when reading text file
    By Andrew McLellan in forum Java
    Replies: 3
    Last Post: 05-09-2001, 05:34 PM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  
HTML5 Development Center
 
 
FAQ
Latest Articles
Java
.NET
XML
Database
Enterprise
Questions? Contact us.
C++
Web Development
Wireless
Latest Tips
Open Source


   Development Centers

   -- Android Development Center
   -- Cloud Development Project Center
   -- HTML5 Development Center
   -- Windows Mobile Development Center