0

although it is possible to do it with a form and submit, I am trying to make the upload of files from javascript to php.

I have slightly modified a code I found on an example for the upload of files from a client (a php file using a javascript) to the server where a PHP file receives the file. This code works for the files that are present on the same folder of the client php file. I am testing this code with xampp so on the localhost folder. Is there any possible way to allow also files from different folders (so that any client would upload files) to be uploaded? Here is the code I am using

client file php

// Getting a file through XMLHttpRequest as an arraybuffer and creating a Blob

var document = document.querySelector("#fileToUpload");
var file = document.getElementById("File1").files[0];

if (document) {


    var xhr = new XMLHttpRequest(),
        blob;

   var file1=document.getElementById("fileToUpload").files[0].name;


    xhr.open("POST", ""+file1, true);



    xhr.responseType = "blob";

    xhr.onreadystatechange = function () {
        window.location.href = "testupload.php?w1=";
        if (xhr.readyState === 4 && xhr.status === 200) {

            /* 
                Create a blob from the response
                Only needed if the responseType isn't already blob
                If it's "arraybuffer", do this:

                blob = new Blob([new Uint8Array(xhr.response)], {type: "image/png"});
            */
            blob = xhr.response;
            var form = new FormData();
            formData.append("file", file);
            form.append("blobbie", blob);

            var xhrForm = new XMLHttpRequest();
            xhrForm.open("POST", "handle_file_upload.php");
            xhrForm.send(form);

            xhrForm.onreadystatechange = function () {
                if (xhrForm.readyState === 4) {
                    console.log(xhrForm.response);
                    rhino.src = xhrForm.response;
                }
            };
        }
    };
    // Send XHR
    xhr.send();
}

};

thanks a lot for any possible advise or sample code you might have. Michele

kele
  • 11
  • 3
  • 1
    You write: "This code works for the files that are present on the same folder of the client php file". What do you mean by that? PHP runs on Server. What is the "client PHP file"?? – Erwin Moller Nov 02 '15 at 14:42
  • Thanks Erwin it was a stupid mistake indeed as it was to be renamed into html and thanks Machavity for the notice, I actually found the issue...it was stopping in formData.append("file", file); thanks again! – kele Nov 02 '15 at 15:05

0 Answers0