1

previously while developing systems whenever i faced a scenario of uploading images to the server through ajax i often use different plugins but now i have to create an interface that is to customized that i have to make everything from scratch!

i have an input type file on my page and what i am doing is i am uploading the image to server via ajax!

now i have developed a snippet let me show you the code first!

html

    <form method="post" id="myform" action="#">
    <div class="image" id="upload-parent">
                                                <input id="upload-image" type="file" name="myfile" accept="image/x-png, image/gif, image/jpeg, image/jpg"/>
                                                <label for="upload-image">+</label>
                                            </div>
</form>

Jquery/Javascript

$("#upload-image").change(function(){
            readURL(this);



//            getting file size and type

//            console.log(this.files[0].type);
//            console.log(this.files[0].size);

//        size in bytes /124 for kb

        });

function readURL(input) {
            if (input.files && input.files[0]) {
                var reader = new FileReader();

                reader.onload = function (e) {

                    $append='<div class="image">'+
                        '<img src="'+reader.result+'" class="img-responsive"/>'+
                        '</div>';

                    $($append).insertBefore("#right-panel .social #max-width #social #upload #images-block #upload-parent");

                    $.ajax({
                        type: 'post',
                        url: 'upload_file_test.php',
                        data: new FormData($("#myform")[0]),
                        contentType:false,
                        processData:false,
                        success: function (data) {

                        }
                    });
                };

                reader.readAsDataURL(input.files[0]);
            }
        }

PHP

<?php
if(isset($_FILES['myfile']['name'])){
    echo "set";

    $target = "uploads/"; //make sure to create a folder named 'uploads' and put it in the same directory that upload.php (this script) is in
    $file_name = $_FILES['myfile']['name'];
    $tmp_dir = $_FILES['myfile']['tmp_name'];

    if(!preg_match('/(gif|jpe?g|png|csv)$/i', $file_name) //set permissible file types
    )
    {
        echo "sorry that file type is not allowed";
    } else {
        move_uploaded_file($tmp_dir, $target . $file_name);
    }
}
else
{
    echo "not set";
}



?>

this code is working 100% fine in case someone else is facing problems creating the above scenarios!

what this snippet is doing is on change of image upload it is previewing the image and then uploading the image on the server.

The issue!

As you can see i am using the form data object to send the image to backend now for this particular scenario i will always need to have a form inside page and more this object method might create issue when input type file are being dynamically generated! or lets suppose i have 50 input type files and i only want to send a specific input type file to backend not all of them! because right now it will send everything to the server which is never an efficient approach if i only want to send one specific file why send everything to the backend?

i did researched alot about it and i can see that the formdata object does alot of things for us out of the box for image processing! what i want is to get the specific input file(Most probably with file reader API) and process it and send only that specific item to the backend! this is what i am trying to accomplish here!

function readURL(input) {
            if (input.files && input.files[0]) {
                var reader = new FileReader();

                reader.onload = function (e) {

                    $append='<div class="image">'+
                        '<img src="'+reader.result+'" class="img-responsive"/>'+
                        '</div>';

                    $($append).insertBefore("#right-panel .social #max-width #social #upload #images-block #upload-parent");

                    $.ajax({
                        type: 'post',
                        url: 'upload_file_test.php',
                        data: "myfile="+reader.result,
                        contentType:false,
                        processData:false,
                        success: function (data) {

                        }
                    });
                };

                reader.readAsDataURL(input.files[0]);
            }
        }

after executing the block of code it just shows me the paraemters to be object file and php is unable to parse it!

can someone guide me how can we send an independent image to the backend without using formdata object?

1 Answer 1

1

TL;DR :)

You can easily process different input[type=file] via it's onChange event

Let's assume, that we have an input

<input type="file" id="myAwesomeFilepicker" />

We want to send file whenever user select file(s), so we are adding an event listener (I don't like jQuery, so I'll write some vanilla JS, hope you will understand):

document.getElementById("myAwesomeFilepicker").addEventListener("change", function(event) {
    var input = event.target
    if (input.files.length > 0) {
        // create an empty FormData instance
        var formData = new FormData()

        // Iterate through picked files
        for (var i = 0; i < input.files.length; i++) {
            var file = input.files[i]
            // append file to the FormData instance
            formData.append(file.name, file)
        }

        /* 
            At this point you can just send formData through AJAX 
            and handle it by your PHP script 
        */

        // Don't forget to clear input
        input.value = ""
    } else {
        // process 0 files picked, if you wish
    }
})

NOTA BENE

FormData has restricted functionality on iOS / MacOS (AFAIK, only FormData.append(...) is present), so be careful with it.


With some small modifications you can make files send after another user's action (for example, button click or something). Hope, my answer was useful for you :)


Yes, I wrote answer by my memory and without testing code. It should work, but there can be some errors :)

Sign up to request clarification or add additional context in comments.

3 Comments

thanks man that was exactly what i was looking for only the specified data gets sent and not additional load on server! just one quick confirmation when were creating the object of formData class it is empty right? like it doesnt take the other fields of the form?
@uneebmeer right, new FormData() is completely empty until you set any field to it with formData.append()
@uneebmeer if you pass some form element to the constructor, like new FormData(myHtmlFormElement), then it will upfilled with named form elements (for example, <input name="login" /> will transformed to a { "login": "<value of input>" } and appended to the FormData like via formData.append("login", "<value of input>")

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.