How to Upload a File to the Server in PHP using JavaScript FormData class



4 dakikalık okuma
December 22, 2017

In this article, I’m going to show you how to use javascript formData class to send the values to the back-end service via AJAX.

Initially, I just create a modal box.

This is our bootsrap modal box in front-end: (HTML)

    <div class="modal fade" id="modal_voice_file">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>
                    <h4 class="modal-title">Upload Voice(mp3) File</h4>
                </div>
                <div class="modal-body">
                    <br/>
                    <center>
                        <span id="pleasewait"></span>
                    </center>
                    <br/>

                    <form method="POST" action="jupload_voice.php"
                          accept-charset="UTF-8" id="upload_voice_form">
                        <div class="form-group">
                            <label for="voice_file" class="col-12">Mp3 File:</label>
                            <div class="col-md-12">
                                <input name="voice_file" type="file" id="voice_file" accept="audio/*">
                                <input type="hidden" name="cur_id" id="cur_id">
                            </div>
                        </div>

                    </form>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
                    <button type="button" class="btn btn-primary" onclick="save_voice_file(event);"
                            id="btn_save_voice_file">Save changes
                    </button>
                </div>
            </div><!-- /.modal-content -->
        </div><!-- /.modal-dialog -->
    </div><!-- /.modal -->

Now, I’m going to use javascript formData to serialize the payload.

      function save_voice_file(event) {
            event.preventDefault();

            var cur_id = $('#cur_id').val();
            var form = $('#upload_voice_form');
            var url = form.attr('action');
            var formData = new FormData(form[0]); // get the 1st file name.

If you want to send other form element’s value we can use append method of the formData. Like that:

      function save_voice_file(event) {
            event.preventDefault();

            var cur_id = $('#cur_id').val();
            var form = $('#upload_voice_form');
            var url = form.attr('action');
            var formData = new FormData(form[0]); // get the 1st file name.
                formData.append('cur_id', cur_id); // get cur_id's value.

Now, I’m sending the values via ajax using formData class : (JavaScript)

      function save_voice_file(event) {
            event.preventDefault();

            var form = $('#upload_voice_form');
            var url = form.attr('action');

            var cur_id = $('#cur_id').val();

            var formData = new FormData(form[0]);
            formData.append('cur_id', cur_id);


            $.ajax({
                type: 'post',
                url: url,
                dataType: 'json',
                data: formData,
                async: true,
                processData: false,
                contentType: false,


                beforeSend: function () {

                    $('#pleasewait').html('Uploading... <br/> <i class="fa fa-spinner fa-pulse fa-lg fa-fw"></i> ');
                    $('#btn_save_voice_file').prop('disabled', true);

                },

                success: function (data) {

                    // $('#pleasewait').empty();
                    $('#btn_save_voice_file').prop('disabled', false);

                    if (data[0].error === false) {
                        location.reload(true);
                    }
                    else {
                        alert(data[0].message);
                    }

                },
                error: function (data) {


                    //  $('#pleasewait').empty();
                    $('#btn_save_voice_file').prop('disabled', false);


                    alert('Something went wrong!');


                }
            });

        }

My back-end PHP code:

<?php
session_start();
require('lib/settings.php'); // this is my personal library for database    operations.

$mydb = new dbHelper($dbname, $dbhost, $dbusername, $dbpassword);

if (isset($_SESSION['username']) == False) {
    die();
}

if (isset($_POST['cur_id'])) {

    $target_dir = "upload_mp3/";
    $filename   = time() . uniqid() . '.mp3';
    $target_dir = $target_dir . basename($filename);

    if (move_uploaded_file($_FILES['voice_file']['tmp_name'], $target_dir)) {

        $update               = [];
        $update['voice_file'] = $filename;
        $mydb -> db_updateData('course_program', $update, 'id=' . $_POST['cur_id']);

        $json[] = [
            'error'   => false,
            'message' => '',
        ];
    }
    else {
        $json[] = [
            'error'   => true,
            'message' => 'Upload Error!',
        ];
    }

}
else {
    $json[] = [
        'error'   => true,
        'message' => 'Not Requested',
    ];
}

echo json_encode($json);
flush();

After uploading the file, I sent the return values as a JSON format. If “error” is true, something went wrong, otherwise, it is successful.


Etiketler: