简体   繁体   中英

How to send a xmlhttp request to a php file to upload an image

I tried to make an ajax image uploader I was wondering how to send an image via a xmlHttpRequest .

Firstly i tried to send with a FormData object

var formdata = new FormData();
formdata.append('file',fileInput.files[0]);

But when I do print_r in the requested php file to _POST and _FILES but the function returned an empty array .

I tried also doing it with only the send() method but it also doesn't work where is the problem

Note : i didn't forgot the "multipart/form-data" in the setHeader.

To use the XML HTTP request features in your application, you must learn to upload files on the background with Ajax

1) Define the input elements for the file upload. Use the upload() method for the button click event to upload the file when the button is click.

 <input type="file" id="uploadfile" name="uploadfile" />
 <input type="button" value="upload" onclick="upload()" />

2) In the upload() method, create a FormData interface instance, and add the file element with the attached file into it. Use the send() method to send the FormData to the server.

  <script>
     var client = new XMLHttpRequest();

     function upload() 
     {
        var file = document.getElementById("uploadfile");

        /* Create a FormData instance */
        var formData = new FormData();
        /* Add the file */ 
        formData.append("upload", file.files[0]);

        client.open("post", "/upload", true);
        client.setRequestHeader("Content-Type", "multipart/form-data");
        client.send(formData);  /* Send to server */ 
     }

     /* Check the response status */  
     client.onreadystatechange = function() 
     {
        if (client.readyState == 4 && client.status == 200) 
        {
           console.log(client.statusText);
        }
     }
  </script>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM