0

Basically I have compressed the image and want to send the blob as a file to php where i can upload it to my database. I can see the nornal post variables to work fine however the $_FILES variable is always empty. I have wrote the code to covert file (IMAGE) to blob and compress it using HTML5 Canvas and then again convert it to file. Then append it to formData and then submitting the form. However it is not happening.

THE RESULT I AM GETTING :


    C:\wamp64\www\proj\working\imageUpload.php:2:
    array (size=4)
      'firstName' => string 'My Name' (length=7)
      'lastName' => string 'My Last Name' (length=12)
      'email' => string 'MyEmail@Email.com' (length=17)
      'phone' => string '7878492048' (length=10)
    C:\wamp64\www\proj\working\imageUpload.php:3:
    array (size=0)
      empty

THE RESULT I WANT

I need the var_dump($_FILES); to not be empty and instead show the files that I am uploading.

<!--*****************************************************************************************

                                            STYLE

*****************************************************************************************-->

<style>
    #form{
        display: grid;
        grid-gap: 10px;
    }
    #form input{
        height: 40px;
        box-sizing: border-box;
        background: lightskyblue;
        border: none;   
    }
</style>
<!--*****************************************************************************************

                                            MARKUP

*****************************************************************************************-->

<form action="./imageUpload.php" method="POST" enctype="multipart/form-data" id="form" name="form">
    <input type="text" name="firstName" id="firstName">
    <input type="text" name="lastName" id="lastName">
    <input type="email" name="email" id="email">
    <input type="tel" name="phone" id="phone">
    <input type="file" id="file1">
    <input type="file" id="file2">
    <input type="submit" value="submit" name="submit">
</form>

<!--*****************************************************************************************

                                            SCRIPT

*****************************************************************************************-->
<script>
    function sendXHRequest(formData, uri,callback) {
      var xhr = new XMLHttpRequest();
      xhr.open('POST', uri, true);
      xhr.send(formData);
      xhr.onreadystatechange = function() {
        if (xhr.readyState>3 && xhr.status==200) { callback(xhr.responseText); }
        };
    }

    document.querySelector('#form').addEventListener('submit',function(){
        event.preventDefault();
        let formData = new FormData(this);
        convertImageToBlob('#file1',formData,'f1');
        convertImageToBlob('#file2',formData,'f2');
        const url = this.getAttribute('action');
        sendXHRequest(formData, url,function(data){
            //console.log(data)
        });
        //form.append("blob",blob, filename);
    });
    function getFileName(){
        var length = 9;
        var result           = '';
        var characters       = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
        var charactersLength = characters.length;
        for ( var i = 0; i < length; i++ ) {
            result += characters.charAt(Math.floor(Math.random() * charactersLength));
        }
        return result;
    }
    function convertImageToBlob(file,formData,name){
        let files = document.querySelector(file);
        const width = 100;
        const height = 100;
        const fileContent = files.files[0];
        fileName = fileContent.name;
        if(fileName){
            let reader = new FileReader();
            reader.readAsDataURL(fileContent);
            reader.onload = event => {
                let img = new Image();
                img.src = event.target.result;
                img.onload = () => {
                    canvas = document.createElement('canvas');
                    canvas.width = width;
                    canvas.height = height;
                    let ctx = canvas.getContext('2d');
                    ctx.canvas.toBlob((blob) => {
                        let f = new File([blob], name, {
                            type: 'image/*',
                            lastModified: Date.now()
                        });
                        formData.append(name, blob, getFileName())
                    }, 'image/*', 0.3);
                }
            }
        }
    }
</script>
  • Reading files is asynchronous (which is why you are using an onload event). You're calling `sendXHRequest` before the `onload` functions are run. You probably want to have `convertImageToBlob` return a promise that resolves when the file is loaded, and then `await` it. – Quentin Apr 07 '20 at 09:11
  • @Quentin Thanks buddy ... but can u please help me with the code here. As I an new. Thank you !! – kalpeshshende Apr 07 '20 at 09:14
  • 1
    There's a duplicate question with plenty of information about promises and timing linked at the top. – Quentin Apr 07 '20 at 09:14

0 Answers0