Ограничить загрузку файла одновременно AJAX - PullRequest
0 голосов
/ 12 февраля 2020

У меня есть форма загрузки нескольких файлов:

<input type="file" name="file" id="file" multiple="multiple" class="form-control-file">

И этот файл js:

jQuery(function($) {
    $(document).ready(function() {
        $("#insertPost").click(function(e){
            e.preventDefault();
            let apiUrl = "#"
            var fd = new FormData();
            var files = $("#file")[0].files;
            for (var i = 0; i < files.length; i++) {
                fd.append("file", files[i]);
                var rowFile =   `<tr class="row">
                                    <td class="col-sm-1" id="stt-${i}"></td>
                                    <td class="col-sm-3" id="name-${i}"></td>
                                    <td class="col-sm-6" id="url-${i}">
                                        <div class="progress" id="progress-${i}">
                                            <div class="progress-bar progress-bar-striped progress-bar-animated  bg-warning" id="progress-bar-${i}" role="progressbar" style="width: 0%;" aria-valuemin="0" aria-valuemax="100"></div>
                                        </div>
                                    </td>
                                    <td class="col-sm-2" id="action-${i}"></td>
                                </tr>`;
                $('#listSuccess').append(rowFile);
                uploadFile(fd, i, files[i]);
            }
            async function uploadFile(fd, i, file) {
                e.preventDefault();
                await $.ajax({
                    type: 'POST',
                    url: "copy-url",
                    processData: false,
                    contentType: false,
                    data: fd,
                    xhr: function () {
                        var xhr = $.ajaxSettings.xhr();
                        if (xhr.upload) {
                            xhr.upload.addEventListener("progress", function (progress) {
                                var total = Math.round((progress.loaded / progress.total) * 100);
                                $("#stt-" + i).text(i);
                                $("#name-" + i).text(file.name);
                                $("#progress-bar-" + i).css({"width": total + "%"});
                                $("#progress-bar-" + i).text(total + "%");
                            }, false);

                            xhr.addEventListener("loadend", function (data) {
                                $("#progress-bar-" + i).closest(".progress").fadeOut(3000, function () {
                                    $(this).remove();
                                });
                                console.log(data)
                                var file_data = JSON.parse(data.target.response);
                                var post_url = file_data.data.post_url
                                if(file_data.data._status == "success") {
                                    $("#url-" + i).text(post_url);
                                } else {
                                    alert(file_data.data.check_role)
                                }
                                $("#action-" + i).append(`<a target="_blank" href="${post_url}"><button class="btn btn-sm btn-success">View</button></a>`)
                            }, false);

                            xhr.addEventListener("error", function () {
                                $("#progress-bar-" + i).closest(".progress")
                                        .addClass("progress-error").find("status-count").text("Error");
                            }, false);

                            xhr.addEventListener("timeout", function (progress) {
                                $("#progress-bar-" + i).closest(".progress")
                                        .addClass("progress-timedout").find("status-count").text("Timed Out");
                            }, false);
                        }
                        return xhr;
                    }
                })
            }
        }); 
    });
});

И следующий файл php:

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    function post($url, $data) {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER ,  false );
        curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        $result = curl_exec($ch);
        curl_close($ch);
        return $result;
    }

    function createPost($title,$fileid,$slug,$file_size,$account_id,$file_url) {
        $create_download_page = array(
            'post_type'     => 'post    ',
            'post_title'    => $title,
            'post_status'   => 'publish',
            'post_name'     => $slug,
            'post_author'   => 1,
            'meta_input'   => array(
                'file_size' => $file_size,
                'file_id' => $fileid
            ),
        );

        $results = wp_insert_post( $create_download_page );

        if( !is_wp_error($results) ) {
            $post_id = $results;
            $post_url = get_permalink($post_id);

            wp_send_json_success(array(
                'file_name' => $title,
                'post_url' => $post_url,
                '_status' => "success"
            ), 200);

        } else {
            wp_send_json_error($results->get_error_message());
        }       
        exit();
    };

    $api_url = '#';

    $getAuth = wp_remote_get($api_url.'authorize?key1='.$key_1.'&key2='.$key_2);
    $authData = json_decode($getAuth['body'],true);
    $access_token = $authData['data']['access_token'];
    $account_id = $authData['data']['account_id'];

    $fullpat = $_FILES['file']['tmp_name'];

    if (function_exists('curl_file_create')) {
        $cFile = curl_file_create($fullpat,$_FILES['file']['type'],$_FILES['file']['name']);
    } else { // 
        $cFile = '@' . realpath($fullpat);
    }

    $post = array('access_token' => $access_token, 'account_id' => $account_id, 'upload_file'=> $cFile);
    $uploadFile = post($api_url."file/upload", $post);
    if($uploadFile) {
        $file_data = json_decode($uploadFile,true);
        $file_data = $file_data['data']['0'];
        $file_id = $file_data['file_id'];
        $slug_url = $file_data['short_url'];
        $size = $file_data['size'];
        $name_file = $file_data['name'];
        $file_size = formatSize($size);
        $file_url = $file_data['url'];
        createPost($name_file,$file_id,$slug_url,$file_size,$account_id,$file_url);
    }
}

В настоящее время, когда я нажимаю «Отправить», все файлы будут опубликованы на сервере, и если у меня будет полный файл одновременно, то произойдет ошибка. Таким образом, у меня есть два решения:

  1. Когда один файл успешно, то после того, как файл будет загружен.
  2. Загрузка двух файлов одновременно, когда их успех будет загружать два файла другой. Но покажет все файлы в html и подождите.

Пожалуйста, покажите мне, как я могу это сделать. Благодаря.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...