Search code examples
javascriptfilepond

Filepond - problem with files previously recorded


I have a filepond where I passed two functions with 'onaddfilestart' and 'onprocessfile' so that, when a file is being sent and the upload has not yet completed, it locks the recording button and only enables it again when processing is finished and the file was sent correctly. Code below:

 //Trava o gravar enquanto não estiver concluído o processamento
            onaddfilestart: (file) => {
                var isLoading = pond.getFiles().filter(x => x.status !== 5).length !== 0;
                if (isLoading) {
                    $("#btnGravar").prop('disabled', true);
                } else {
                    $("#btnGravar").prop('disabled', false);
                }

            },
            onprocessfile: (file) => {
                var isLoading = pond.getFiles().filter(x => x.status !== 5).length !== 0;
                if (isLoading) {
                    $("#btnGravar").prop('disabled', true);
                } else {
                    $("#btnGravar").prop('disabled', false);
                }
            },

However, whenever I reload the page with the saved files, it locks the recording button, not allowing to save changes (Only if I remove the file and upload it again, so when completing the new upload, it unlocks the button).

I tried to solve it by passing the 'oninit' function to check if there are files loaded and disabling the recording button only if there is no file in the file list, but in the first example (I'll be putting it below) it unlocks when passing through the function, but when exiting her, it blocks the button again (Even if I put it as the last instruction in the code) and in the second example, it worked in parts. It sometimes comes unlocked, but most of the time, locked. The isLoading variable, which verifies if there is processing in the filepond, comes either as true or as false, depending on the delay of the browser (My guess) to load the previously saved file. When it goes fast, it unlocks, when it takes a while, it comes as true and lock the button. code below

Example 1:

// Código para verificar se há arquivos carregados e habilitar o botão de gravar
          oninit: () => {
                var isLoading = pond.getFiles().filter(x => x.status !== 5).length !== 0;
                if (!isLoading) {
                    $("#btnGravar").prop('disabled', false);
                }
            },

Example 2:

// Código para verificar se há arquivos carregados e habilitar o botão de gravar
      oninit: () => {
        const files = pond.getFiles();
        const isLoading = files.some(file => file.status !== FilePond.FILE_PROCESSING_COMPLETE);
        $("#btnGravar").prop('disabled', isLoading);
      },

Can anyone tell me where my mistake is? Why does the second example sometimes work and sometimes not? Is there any way I can set a cooldown for it to check only when the site has completely loaded if there are already saved files?

Thanks in advance.

Below the entire filepond code currently:

 function createFilePond() {
        const pond = FilePond.create($('#filepondVideo')[0], {


            //Trava o gravar enquanto não estiver concluído o processamento
            onaddfilestart: (file) => {
                var isLoading = pond.getFiles().filter(x => x.status !== 5).length !== 0;
                if (isLoading) {
                    $("#btnGravar").prop('disabled', true);
                } else {
                    $("#btnGravar").prop('disabled', false);
                }

            },
            onprocessfile: (file) => {
                var isLoading = pond.getFiles().filter(x => x.status !== 5).length !== 0;
                if (isLoading) {
                    $("#btnGravar").prop('disabled', true);
                } else {
                    $("#btnGravar").prop('disabled', false);
                }
            },


            // add the Image Crop default aspect ratio
            maxFiles: 1,
            imagePreviewTransparencyIndicator: "grid",
            imageValidateSizeLabelImageSizeTooSmall: "Imagem menor do que o recomendadas",
            imageValidateSizeLabelImageSizeTooBig: "Imagem maior que o  recomendadas",
            imagePreviewMarkupShow: false,
            imageResizeTargetWidth: 1080,
            imageResizeMode: 'cover',
            imageResizeUpscale: false,
            labelButtonDownloadItem: 'custom label', // by default 'Download file'
            allowDownloadByUrl: true, // by default downloading by URL disabled
            server: {
                process: {
                    url: 'js/sqlscope_testeVideo.php',
                    method: 'POST',
                    timeout: 7000,
                    onload: (formData) => {
                        verificaVideo(formData);
                        return formData;
                    },
                    onerror: null,
                    ondata: (formData) => {
                        formData.append("funcao", "processFilepond");
                        return formData;
                    },
                },
                revert: { //nao pega o ondata no sqlscope somente o url. -> https://pqina.nl/filepond/docs/api/server/#revert
                    url: 'js/sqlscope_removeArquivo.php',
                    method: 'POST',
                    timeout: 7000,
                    onload: (formData) => {
                        hideVideo();
                        return formData;
                    },
                    onerror: null,
                },
                
                load: (uniqueFileId, load) => {
                    // you would get the file data from your server here
                    fetch(uniqueFileId)
                        .then(res => res.blob())
                        .then(load);
                },
            },
            files: JSON.parse($("#jsonFilepondVideo").val()),

            // Código para verificar se há arquivos carregados e habilitar o botão de gravar
            oninit: () => {
                const files = pond.getFiles();
                const isLoading = files.some(file => file.status !== FilePond.FILE_PROCESSING_COMPLETE);
                $("#btnGravar").prop('disabled', isLoading);
            },

        });
        $('#filepondVideo').css('height', '160px');
        
    }

Solution

  • After some days trying I've made up with a solution. To help others with the same doubts, I'll be posting the code below:

    function createFilePond() {
    
            const files = JSON.parse($("#jsonFilepondVideo").val());
    
            const pond = FilePond.create($('#filepondVideo')[0], {
                onaddfilestart: (file) => {
                    // Verifica se o arquivo já foi salvo no servidor
                    if (file.serverId) {
                        // Arquivo já foi salvo, mantém o botão desbloqueado
                        return;
                    }
                    // Arquivo novo, bloqueia o botão
                    $("#btnGravar").prop('disabled', true);
                },
    
                onprocessfile: (file) => {
                    if (pond.getFiles().filter(x => x.status !== FilePond.FileStatus.PROCESSING).length === 0) {
                        $("#btnGravar").prop('disabled', false);
                    }
                },
    
                onprocessfileprogress: (file, progress) => {
                    if (progress === 1) {
                        $("#btnGravar").prop('disabled', false);
                    }
                },
    
                // add the Image Crop default aspect ratio
                maxFiles: 1,
                imagePreviewTransparencyIndicator: "grid",
                imageValidateSizeLabelImageSizeTooSmall: "Imagem menor do que o recomendadas",
                imageValidateSizeLabelImageSizeTooBig: "Imagem maior que o  recomendadas",
                imagePreviewMarkupShow: false,
                imageResizeTargetWidth: 1080,
                imageResizeMode: 'cover',
                imageResizeUpscale: false,
                labelButtonDownloadItem: 'custom label', // by default 'Download file'
                allowDownloadByUrl: true, // by default downloading by URL disabled
                server: {
                    process: {
                        url: 'js/sqlscope_testeVideo.php',
                        method: 'POST',
                        timeout: 7000,
                        onload: (formData) => {
                            verificaVideo(formData);
                            return formData;
                        },
                        onerror: null,
                        ondata: (formData) => {
                            formData.append("funcao", "processFilepond");
                            return formData;
                        },
                    },
                    revert: { //nao pega o ondata no sqlscope somente o url. -> https://pqina.nl/filepond/docs/api/server/#revert
                        url: 'js/sqlscope_removeArquivo.php',
                        method: 'POST',
                        timeout: 7000,
                        onload: (formData) => {
                            hideVideo();
                            return formData;
                        },
                        onerror: null,
                    },
                    load: (uniqueFileId, load) => {
                        fetch(uniqueFileId)
                            .then(res => res.blob())
                            .then(load);
                    },
                },
                files: files
            });
    
            // Verifica se há arquivos novos no filepond
            const newFiles = pond.getFiles().filter(file => !file.serverId);
            if (newFiles.length > 0) {
                $("#btnGravar").prop('disabled', true);
            } else {
                $("#btnGravar").prop('disabled', false);
            }
    
            $('#filepondVideo').css('height', '160px');
    
        }