Google API ничего не возвращает, если размер загруженного файла превышает 30 МБ с использованием PHP - PullRequest
1 голос
/ 29 мая 2020

Почему мой код PHP ничего не возвращает при загрузке файла размером более 30 МБ, но он работает на локальном хосте, проблема на стороне сервера. Иногда он говорит об ошибке 503 или об ошибке: NET CONNECTION RESET. но в основном ничего не возвращает.

когда я загружаю файл размером менее 25 МБ, они загружаются довольно тихо.

А также, если кто-то может помочь мне с индикатором выполнения, пока данные загружаются на диск , в моем коде прогресс отображается, но после загрузки файла, а не во время загрузки (я читал о getURI и ... но не понял должным образом), может ли кто-нибудь направить меня сюда?

I Я использую V3 Google-drive-api.

ИНДЕКС. php

<!DOCTYPE html>
<html lang="es">
    <head>
        <meta charset="UTF-8">

    <title>Google Drive Example App</title>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
    <!-- Latest compiled and minified CSS -->
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
    <!-- Optional theme -->
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap-theme.min.css" integrity="sha384-rHyoN1iRsVXV4nD0JutlnGaslCJuC7uwjduW9SVrLvRYooPp2bWYgmgJQIXwl/Sp" crossorigin="anonymous">
    <!-- Latest compiled and minified JavaScript -->
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script>
    <script>
        $(function () {
            $('#btn').click(function () {
                $('.myprogress').css('width', '0');
                $('.msg').text('');
                var filename = $('#filename').val();
                var myfile = $('#myfile').val();
                var discription = $('#discription').val();
                if (filename == '' || myfile == '') {
                    alert('Please enter file name and select file');
                    return;
                }
                var formData = new FormData();
                formData.append('pdf', $('#myfile')[0].files[0]);
                formData.append('name', filename);
                formData.append('discription', discription);
                $('#btn').attr('disabled', 'disabled');
                 $('.msg').text('Uploading in progress...');
                $.ajax({
                    url: 'action.php',
                    data: formData,
                    processData: false,
                    contentType: false,
                    type: 'POST',
                    // this part is progress bar
                    xhr: function () {
                        var xhr = new window.XMLHttpRequest();
                        xhr.upload.addEventListener("progress", function (evt) {
                            if (evt.lengthComputable) {
                                var percentComplete = evt.loaded / evt.total;
                                percentComplete = parseInt(percentComplete * 100);
                                $('.myprogress').text(percentComplete + '%');
                                $('.myprogress').css('width', percentComplete + '%');
                            }
                        }, false);
                        return xhr;
                    },
                    success: function (data) {
                        $('.msg').text(data);
                        $('#btn').removeAttr('disabled');
                    }
                });
            });
        });


    </script>
 </head>
 <body>
      <div class="container">
            <div class="row">
                <h3>File Upload</h3>
                <form id="myform" method="post">
                    <div class="form-group">
                        <label>File name: </label>
                        <input class="form-control" type="text" id="filename" /> 
                    </div>
                    <div class="form-group">
                        <label>File Discription: </label>
                        <input class="form-control" type="text" id="discription" /> 
                    </div>
                    <div class="form-group">
                        <label>Select file: </label>
                        <input class="form-control" type="file" id="myfile" />
                    </div>
                    <div class="form-group">
                        <div class="progress">
                            <div class="progress-bar progress-bar-success myprogress" role="progressbar" style="width:0%">0%</div>
                        </div>
                        <div class="msg"></div>
                    </div>
                    <input type="button" id="btn" class="btn-success" value="Upload" />
                </form>
            </div>
        </div>
    </body>

</html>

ДЕЙСТВИЕ. php

<?php

   ini_set('upload_max_filesize', '1000M');
   ini_set('post_max_size', '1000M');
   set_time_limit(5000);

if(isset($_FILES['pdf']) && isset($_POST['name'])){
    $name = $_POST['name'];
    if($name == ''){
        echo "file name is Empty";
    }else{
        $discription = $_POST['discription'];
        $target_dir = "files/";
        $file_name = basename($_FILES["pdf"]["name"]);
        $filesize = $_FILES['pdf']['size'];
        $FileType = strtolower(pathinfo($file_name,PATHINFO_EXTENSION));
        $file = "test_file.".$FileType;
        $file_path = $target_dir . $file;
        $tmpname = $_FILES['pdf']['tmp_name'];
        $upload = move_uploaded_file($tmpname, $file_path);

        if($upload == true){
            include_once __DIR__ . '/google-api-php-client-master/vendor/autoload.php';
            $client = new Google_Client();
            $client->setAuthConfig('credentials.json');
            $client->addScope('https://www.googleapis.com/auth/drive.file');

            $service = new Google_Service_Drive($client);
            $service = new Google_Service_Drive($client);
            $client->getAccessToken();

            $file = new Google_Service_Drive_DriveFile();
            $chunkSizeBytes = 1 * 1024 * 1024;
            $client->setDefer(true);

            $finfo = finfo_open(FILEINFO_MIME_TYPE);

            $parentId = "PARENT_FOLDER_ID";
            $file->setParents(array($parentId));

            $mime_type = finfo_file($finfo, $file_path);
            $file->setName($name);
            $file->setDescription($discription);

            $response = $service->files->create($file);                

            // Create a media file upload to represent our upload process.
            $media = new Google_Http_MediaFileUpload(
              $client,
              $response,
              $mime_type,
              null,
              true,
              $chunkSizeBytes
            );
            $media->setFileSize(filesize($file_path));

            function readVideoChunk ($handle, $chunkSize){
                $byteCount = 0;
                $giantChunk = "";
                while (!feof($handle)) {
                    $chunk = fread($handle, $chunkSize);
                    $byteCount += strlen($chunk);
                    $giantChunk .= $chunk;
                    if ($byteCount >= $chunkSize)
                    {
                        return $giantChunk;
                    }
                }
                return $giantChunk;
            }

            // Upload the various chunks. $status will be false until the process is complete.
            $status = false;
            $handle = fopen($file_path, "rb");
            while (!$status && !feof($handle)) {
                // An example of a read buffered file is when reading from a URL
                $chunk = readVideoChunk($handle, $chunkSizeBytes);
                $status = $media->nextChunk($chunk);
               //if want to show the progress bar too but not working while uploading , but it shows the uploaded chunks after the files is been uploaded. 
                if(!$status){ //nextChunk() returns 'false' whenever the upload is still in progress
                    echo 'sucessfully uploaded file up to byte ' . $media->getProgress() . ' which is ' . ( $media->getProgress() / $chunkSizeBytes ) . '% of the whole file';
                }
            }
            $result = false;
            if ($status != false) {
                $result = $status;
            }

            $file_id = $status['id'];

            fclose($handle);

            // Reset to the client to execute requests immediately in the future.
            $client->setDefer(false);
           //i am manually creating the wbViewLink by the ID i am getting in response 
            $webViewLink = "https://drive.google.com/file/d/$file_id/view?usp=drivesdk";

            $myobj = new StdClass();
            $myobj->{'alt_link'} = $webViewLink;
            $myobj->{'size'} = $filesize;
            print_r($myobj);
        }else{
            echo "upload failed";
        }
    }
  }
?>

Кто-нибудь может мне здесь помочь? Я использую сервисный аккаунт, как вы можете видеть для аутентификации пользователя от моего имени ...

когда все в порядке, результат будет примерно таким {image}

но когда я загружаю файл, результат превышает 30 МБ (только на сервере, на локальном хосте все работает нормально) {image}

также вы можете увидеть на втором изображении статус в ОК, но по-прежнему нет ответа.

1 Ответ

1 голос
/ 29 мая 2020

Вы не всегда можете переопределить настройку размера загрузки с помощью ini_set, в зависимости от хостинг-провайдера. Попробуйте это в своем .htaccess:

php_value upload_max_filesize 100M
php_value post_max_size 100M
...