0

Estoy tratando de subir archivos PSD desde la parte de admin de mi sistema.

La característica de los PSD que están tratando de subir es que son muy pesados, en promedio de 200 MB, y pues como es de esperarse, la petición se muere.

De manera local, me aparecía el siguiente error: introducir la descripción de la imagen aquí

Entonces lo que hice, fue modificar de manera local los archivos php.ini con lo siguiente:

memory_limit=-1
max_input_time=600
post_max_size=300M
upload_max_filesize=300M
max_input_vars=100000000

Además de modificar también el nginx.conf también de manera local, con lo siguiente:

http {
include mime.types;
default_type  application/octet-stream;

sendfile on;
keepalive_timeout 65;
server_names_hash_bucket_size 64;
client_max_body_size 300M;

client_header_timeout 3000;
client_body_timeout 3000;
fastcgi_read_timeout 3000;
client_max_body_size 300M;
fastcgi_buffers 8 128k;
fastcgi_buffer_size 128k;
}

Implementé una carga por AJAX para ese archivo especial, primero pedí que fuera un .zip para reducir la carga lo más posible. Y luego codifiqué esto:

$(document).on('change', 'input[name="psd_1"]', function() {
    var input_psd = $(this);
    uploadPsdAjax(input_psd, 1);
});

function uploadPsdAjax(input_psd, number) {
    var _URL = window.URL || window.webkitURL;
    var file = (input_psd[0].files[0]);
    //var blob_url = window.URL.createObjectURL(file); // No se usa

    var product_id = $('input[name="product"]').val()

    var action = "/upload-psd"; //Route in web.php

    var original_label = input_psd.closest('.backstrap-file').siblings('label');
    original_label.text(original_label.text() + ' Cargando...');

    var formData = new FormData();
    formData.append('file', file);
    formData.append('product_id', product_id);
    formData.append('number', number);
    console.log(formData.get('file'), formData.get('number')); // In log you cannot see logging only formData, use .get()

    new Noty({
        text: 'Empezando la subida del PSD para la perspectiva ' + number,
        type: 'info',
        animation: {
            open: 'animated bounceInRight', // Animate.css class names
            close: 'animated bounceOutRight' // Animate.css class names
        }
    }).show();

    if (product_id) {
        $.ajax({
            type: 'POST',
            url: action,
            data: formData,
            /*THIS MUST BE DONE FOR FILE UPLOADING*/
            contentType: false,
            processData: false,

        }).done(function(response) {
            console.log("DONE", response);
            new Noty({
                text: 'Subida exitosa. El archivo PSD se asignó correctamente',
                type: "success",
                animation: {
                    open: 'animated bounceInRight', // Animate.css class names
                    close: 'animated bounceOutRight' // Animate.css class names
                }
            }).show();
        }).fail(function(data) {
            console.log("FAIL", data.responseText);
            var html_string = data.responseText;
            html = $(html_string);
            console.log(html.toArray()[1]['innerText']);

            if (html.toArray()[1]['innerText'] == "504 Gateway Time-out") {
                new Noty({
                    text: 'Subida exitosa. El archivo PSD se asignó correctamente',
                    type: "success",
                    animation: {
                        open: 'animated bounceInRight', // Animate.css class names
                        close: 'animated bounceOutRight' // Animate.css class names
                    }
                }).show();
            } else {
                new Noty({
                    text: 'Algo falló en la subida del PSD',
                    type: "error",
                    animation: {
                        open: 'animated bounceInRight', // Animate.css class names
                        close: 'animated bounceOutRight' // Animate.css class names
                    }
                }).show();
            }
        });
    } else {
        new Noty({
            text: 'No puedes subir PSDs cuando creas un nuevo product, guárdalo, regresa y carga de uno en uno',
            type: "info",
        }).show();
    }
}

Lo que hace es mandar el request con ciertas condiciones en el AJAX, hacia el siguiente método de un controlador:

public function uploadPsd(Request $request)
{
    $response['code'] = "200";

    // Set which bucket to work in
    $bucketName = "myproject.appspot.com";

    // Get local file for upload testing
    $fileContent = file_get_contents($_FILES["file"]["tmp_name"]);

    // Defining path
    $cloudPath = 'test/psd1.zip';

    $isSucceed = $this->uploadFile($bucketName, $fileContent, $cloudPath); 

    if ($isSucceed == true) {
        $response['msg'] = 'SUCCESS: to upload ' . $cloudPath . PHP_EOL;
        // TEST: get object detail (filesize, contentType, updated [date], etc.)
        $response['data'] = $this->getFileInfo($bucketName, $cloudPath);
        //Save path DB...
    } else {
        $response['code'] = "201";
        $response['msg'] = 'FAILED: to upload ' . $cloudPath . PHP_EOL;
    }
    header("Content-Type:application/json");
    return json_encode($response);
}

Y todo se sube correctamente, cuando trabajo en local, aparece en el bucket de Google directamente, con éxito, pero aparece el error 504 (Gateway Time-out), pero repito, el archivo se sube correctamente, a pesar de que manda ese error.

Cuando lo probé en línea, ya en el servidor producción, el AJAX inmediatamente mandaba el error Your client issued a request that was too large a lo que pensé que podría solucionarse creando un archivo nginx-app.conf con las variables antes mencionadas, pero sin éxito. Consulté esta pregunta aquí.

Estoy muy cerca de lograr la carga, funciona con "éxito" en local y sube al bucket el .zip, a pesar de marcar 504 (Gateway Time-out), de manera local.

En producción, no puedo avanzar más, inmediatamente dice Your client issued a request that was too large Error 413 (Request Entity Too Large)

13
  • Cuál es el límite de tu variable client_max_body_size en /etc/nginx/nginx.conf? el 23 oct. 2020 a las 21:59
  • Hola, en la consola de Google Cloud, en el directorio etc/ no existe el directorio nginx/ :(
    – Chris
    el 23 oct. 2020 a las 22:16
  • Pero no deberías probar que tu proceso funcione primero en tu entorno local? Revisa esa variable en tu local y aumentala para que verifiques que todo funcione bien el 23 oct. 2020 a las 22:18
  • No está dentro de tu C:/nginx/? Depende de donde instalaste nginx el 23 oct. 2020 a las 22:26
  • @L.Flor encontré ese archivo, como uso valet, el directorio está muy escondido. EL valor que tengo en nginx.conf para client_max_body_size es 300M. Aún así sigue saliendo error 413 Request Entity Too Large. Usé composer dump-autoload y php artisan optimize
    – Chris
    el 26 oct. 2020 a las 18:16

1 respuesta 1

0

Una solución eficiente es Cargar archivos grandes en fragmentos o Chunks y puedes desarrollarla combinando resumable.js y laravel-chunk-upload así puedes cargar archivos grandes de hasta 10 GB o más sin ningún problema.

Este es un ejemplo rapido para que vean como cargo un video en fragmentos:

FrontEnd:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" integrity="sha384-rbsA2VBKQhggwzxH7pPCaAqO46MgnOM80zW1RWuH61DGLwZJEdK2Kadq2F9CUG65" crossorigin="anonymous">

    <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js" integrity="sha384-kenU1KFdBIe4zVF0s0G1M5b4hcpxyD9F7jL+jjXkk+Q2h455rYXK/7HAuoJl+0I4" crossorigin="anonymous"></script>
    <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.min.js" integrity="sha384-cuYeSxntonz0PPNlHhBs68uyIAVpIIOZZ5JqeqvYYIcEL727kskC66kF92t6Xl2V" crossorigin="anonymous"></script>
    <script src="https://code.jquery.com/jquery-3.6.3.min.js" integrity="sha256-pvPw+upLPUjgMXY0G+8O0xUf+/Im1MZjXxxgOcBQBXU=" crossorigin="anonymous"></script>
    <script src="/assets/js/resumable.min.js"></script>
    
</head>
<body>

    <div class="container pt-4">
        <div class="row justify-content-center">
            <div class="col-md-8">
                <div class="card">
                    <div class="card-header text-center">
                        <h5>Upload File</h5>
                    </div>

                    <div class="card-body">
                        <div id="upload-container" class="text-center">
                            <button id="browseFile" class="btn btn-primary">Brows File</button>
                        </div>
                        <div  style="display: none" class="progress mt-3" style="height: 25px">
                            <div class="progress-bar progress-bar-striped progress-bar-animated" role="progressbar" aria-valuenow="75" aria-valuemin="0" aria-valuemax="100" style="width: 75%; height: 100%">75%</div>
                        </div>
                    </div>

                    <div class="card-footer p-4" style="display: none">
                        <video id="videoPreview" src="" controls style="width: 100%; height: auto"></video>
                    </div>
                </div>
            </div>
        </div>
    </div>  

    <script type="text/javascript">
        let browseFile = $('#browseFile');
        let resumable = new Resumable({
                target: '{{ route('files.upload.large') }}',
                query:{_token:'{{ csrf_token() }}'} ,// CSRF token
                fileType: ['mp4'],
                chunkSize: 10*1024*1024, // default is 1*1024*1024, this should be less than your maximum limit in php.ini
                headers: {
                    'Accept' : 'application/json'
                },
                testChunks: false,
                throttleProgressCallbacks: 1,
            });

        resumable.assignBrowse(browseFile[0]);

        resumable.on('fileAdded', function (file) { // trigger when file picked
            showProgress();
            resumable.upload() // to actually start uploading.
        });

        resumable.on('fileProgress', function (file) { // trigger when file progress update
            updateProgress(Math.floor(file.progress() * 100));
        });

        resumable.on('fileSuccess', function (file, response) { // trigger when file upload complete
            response = JSON.parse(response);
            $('#videoPreview').attr('src', response.path);
            $('.card-footer').show();
        });

        resumable.on('fileError', function (file, response) { // trigger when there is any error
            console.log(response);
        });


        let progress = $('.progress');
        function showProgress() {
            progress.find('.progress-bar').css('width', '0%');
            progress.find('.progress-bar').html('0%');
            progress.find('.progress-bar').removeClass('bg-success');
            progress.show();
        }

        function updateProgress(value) {
            progress.find('.progress-bar').css('width', `${value}%`)
            progress.find('.progress-bar').html(`${value}%`)
        }

        function hideProgress() {
            progress.hide();
        }
    </script>
    
</body>
</html>

puedes usar el resumable.js de este CDN: https://cdn.jsdelivr.net/npm/[email protected]/resumable.min.js

BackEnd

Ejecuta este comando para instalar en tu projecto de laravel:

composer require pion/laravel-chunk-upload

Aqui esta el controlador:

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Facades\File;
use Pion\Laravel\ChunkUpload\Exceptions\UploadMissingFileException;
use Pion\Laravel\ChunkUpload\Handler\AbstractHandler;
use Pion\Laravel\ChunkUpload\Handler\HandlerFactory;
use Pion\Laravel\ChunkUpload\Receiver\FileReceiver;

class UploadController extends Controller
{
    public function index(){

        return view('upload.index');
    }

    public function process(Request $request){
        $receiver = new FileReceiver('file', $request, HandlerFactory::classFromRequest($request));

        if (!$receiver->isUploaded()) {
            // file not uploaded
        }

        $fileReceived = $receiver->receive(); // receive file
        if ($fileReceived->isFinished()) { // file uploading is complete / all chunks are uploaded
            $file = $fileReceived->getFile(); // get file
            $extension = $file->getClientOriginalExtension();
            $fileName = str_replace('.'.$extension, '', $file->getClientOriginalName()); //file name without extenstion
            $fileName .= '_' . md5(time()) . '.' . $extension; // a unique file name

            $disk = Storage::disk('public');
            $path = $disk->putFileAs('videos', $file, $fileName);

            // delete chunked file
            unlink($file->getPathname());
            return [
                'path' => asset('storage/' . $path),
                'filename' => $fileName,
                'disk' => $disk
            ];
        }

        // otherwise return percentage information
        $handler = $fileReceived->handler();
        return [
            'done' => $handler->getPercentageDone(),
            'status' => true
        ];
    }
}

Tu Respuesta

By clicking “Publica tu respuesta”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

¿No es la respuesta que buscas? Examina otras preguntas con la etiqueta o formula tu propia pregunta.