Frank Eno
Frank Eno

Reputation: 2649

How to upload an image into a folder with blob:http link using PHP and JavaScript?

I am trying to upload an image to an uploads folder in my server using PHP and JS. I'm a beginner.

Here's my code:

signup.php - where I select an image from my computer and display it in the page:

<img id="avatar-img" class="img-responsive" src="assets/img/user_avatar.png" height="64" width="64" />

</div>



    <div class="fileupload-preview fileupload-exists thumbnail" style="height: 120px; width: 120px"></div>

    <span class="btn btn-file btn-info">
    <span class="fileupload-new">Select image</span>
    <span class="fileupload-exists">Change</span>

    <!-- ImageData input -->
    <input id="imageData" name="file" type="file" accept="image/*"/>

    ...

<!-- Image Reader JS function -->
            <script >

            document.getElementById("imageData").onchange = function () {
                var reader = new FileReader();
                reader.onload = function (data) {

                    document.getElementById("avatar-img").src = data.target.result;
                    console.log(data.target.result);
                };

                // Read the image file as a data URL.
                var blob = (window.URL || window.webkitURL).createObjectURL(this.files[0]);
                document.getElementById('fileURL').value = blob;



                // Upload the selected image automatically into the 'uploads' folder
                var filename = "avatar.jpg";
                var data = new FormData();
                data.append('file', blob);

                $.ajax({
                    url :  "upload.php",
                    type: 'POST',
                    data: data,
                    contentType: false,
                    processData: false,
                    success: function(data) {
                        alert(data);

                    }, error: function() {
                        alert("Something went wrong, try again!");
                    }
                });
            };       
</script>

In this signup.php file, I successfully get a blob:http link into an input text field after I select an image, something like: blob:http://www.example.com/7d5aac71-5eb5-41b3-a14e-e1ae680eb337

NOTE: check the picture below, it shows the input text field, it will be hidden later, now it's visible only for test purposes:

enter image description here

Here's my upload.php file:

<?php 

    if ($_FILES["file"]["error"] > 0) {
        echo "Error: " . $_FILES["file"]["error"] . "<br />";
    } else {
        move_uploaded_file($_FILES["file"]["tmp_name"],"uploads/" . $_FILES["file"]["name"]);

        // Get fileURL path and show success alert
        global $fileURL;
        $fileURL = "uploads/" . $_FILES["file"]["name"];

        echo $fileURL;

  }

?>

So, probably there's something wrong in the upload.php file, I don't know, because signup.php shows an alert that says "uploads/" only after I select an image, which is the echo it gets from upload.php, but if I enter my uploads folder, I see no image in it.

NOTE: My uploads folder is not in the root of my server, but it's in the root of the directory that hosts all my PHP files, which is something like http://example.com/mysitename, so the upload folder's link is http://example.com/mysitename/uploads.

Upvotes: 2

Views: 8326

Answers (1)

Ferhat BAŞ
Ferhat BAŞ

Reputation: 797

Hi I have changed just 3 code block that are

if (document.getElementById('imageData').files[0]) {
    reader.readAsDataURL(document.getElementById('imageData').files[0]);
}

instead of

var blob = (window.URL || window.webkitURL).createObjectURL(this.files[0]);
document.getElementById('fileURL').value = blob;

and move your ajax request in prview onload event

document.getElementById("avatar-img").onload = function () {
        // Upload the selected image automatically into the 'uploads' folder
        var filename = "avatar.jpg";
        var data = new FormData();
        data.append('file', document.getElementById('imageData').files[0]);


        $.ajax({
            url :  "upload.php",
            type: 'POST',
            data: data,
            contentType: false,
            processData: false,
            success: function(data) {
                alert(data);

            }, error: function() {
                alert("Something went wrong, try again!");
            }
        });
    };

and correct file element use in data.append

data.append('file', document.getElementById('imageData').files[0]);

and you can see complete code block

document.getElementById("imageData").onchange = function () {
var reader = new FileReader();
reader.onload = function (data) {

    document.getElementById("avatar-img").src = data.target.result;
    console.log(data.target.result);
    document.getElementById("avatar-img").onload = function () {
        // Upload the selected image automatically into the 'uploads' folder
        var filename = "avatar.jpg";
        var data = new FormData();
        data.append('file', document.getElementById('imageData').files[0]);


        $.ajax({
            url :  "upload.php",
            type: 'POST',
            data: data,
            contentType: false,
            processData: false,
            success: function(data) {
                alert(data);

            }, error: function() {
                alert("Something went wrong, try again!");
            }
        });
    };
};
if (document.getElementById('imageData').files[0]) {
    reader.readAsDataURL(document.getElementById('imageData').files[0]);
}
/*// Read the image file as a data URL.
var blob = (window.URL || window.webkitURL).createObjectURL(this.files[0]);
document.getElementById('fileURL').value = blob;
*/
};

Upvotes: 4

Related Questions