0

There is a webpage on my website where user can upload pictures. I want to set the limit of the pictures to be uploaded upto 2mb. Currently it uploads image of all sizes. If the picture is less than 2mb it will go along the normal path and get uploaded and if it is greater than 2mb a pop up should show error message. Can anybody help me in how to do this with javascript alone? Any help would be appreciated. Thanks!

Follow the script below, just help me to set the size limit of the image, if not someone would be able to upload a 5gb image and overload my server.

        // Iniciando biblioteca
                                                    var resize = new window.resize();
                                                    resize.init();

                                                    // Declarando variáveis
                                                    var imagens;
                                                    var imagem_atual;

                                                    // Quando carregado a página
                                                    $(function ($) {

                                                        // Quando selecionado as imagens
                                                        $('#imagem').on('change', function () {
                                                            enviar();
                                                        });

                                                    });


                                                    /*
                                                     Envia os arquivos selecionados
                                                     */
                                                    function enviar()
                                                    {
                                                        // Verificando se o navegador tem suporte aos recursos para redimensionamento
                                                        if (!window.File || !window.FileReader || !window.FileList || !window.Blob) {
                                                            alert('O navegador não suporta os recursos utilizados pelo aplicativo');
                                                            return;
                                                        }

                                                        // Alocando imagens selecionadas
                                                        imagens = $('#imagem')[0].files;

                                                        // Se selecionado pelo menos uma imagem
                                                        if (imagens.length > 0)
                                                        {
                                                            // Definindo progresso de carregamento
                                                            $('#progresso').attr('aria-valuenow', 0).css('width', '35%').html('Carregando..');
                                                                // Escondendo campo de imagem
                                                            $('#imagem').hide();

                                                            // Iniciando redimensionamento
                                                            imagem_atual = 0;
                                                            redimensionar();
                                                        }
                                                    }

                                                        /*
                                                         Redimensiona uma imagem e passa para a próxima recursivamente
                                                         */
                                                        function redimensionar()
                                                        {
                                                            // Se redimensionado todas as imagens
                                                            if (imagem_atual > imagens.length)
                                                            {
                                                                // Definindo progresso de finalizado
                                                                $('#progresso').html('Imagem enviada com sucesso');

                                                                // Limpando imagens
                                                                limpar();

                                                                // Exibindo campo de imagem
                                                                $('#imagem').show();

                                                                // Finalizando
                                                                return;
                                                            }

                                                            // Se não for um arquivo válido
                                                            if ((typeof imagens[imagem_atual] !== 'object') || (imagens[imagem_atual] == null))
                                                            {
                                                                // Passa para a próxima imagem
                                                                imagem_atual++;
                                                                redimensionar();
                                                                return;
                                                            }

                                                            // Redimensionando
                                                            resize.photo(imagens[imagem_atual], 800, 'dataURL', function (imagem) {

                                                                // Salvando imagem no servidor
                                                                $.post('ajax/salvar.php', {imagem: imagem}, function() {

                                                                    // Definindo porcentagem
                                                                    var porcentagem = (imagem_atual + 1) / imagens.length * 100;

                                                                    // Atualizando barra de progresso
                                                                    $('#progresso').text(Math.round(porcentagem) + '%').attr('aria-valuenow', porcentagem).css('width', porcentagem + '%');

                                                                    // Aplica delay de 1 segundo
                                                                    // Apenas para evitar sobrecarga de requisições
                                                                    // e ficar visualmente melhor o progresso
                                                                    setTimeout(function () {
                                                                        // Passa para a próxima imagem
                                                                        imagem_atual++;
                                                                        redimensionar();
                                                                    }, 100);

                                                                });

                                                            });
                                                            }

                                                              /*
                                                         Limpa os arquivos selecionados
                                                         */

I need help because I dont know how to fix that in the code above. I am not a javascript coder. I am just tryng to help a friend that dont speak english. SOmeone please write the part of the code where it verify the filesize before allowing to upload, please

ALessandro
  • 25
  • 7
  • 1
    Possible duplicate of [JavaScript file upload size validation](https://stackoverflow.com/questions/3717793/javascript-file-upload-size-validation) – Tyr Aug 26 '17 at 22:11
  • 1
    You would do it at the server side, not with clientside validation. – Bergi Aug 26 '17 at 22:18

1 Answers1

0

File objcet offer a property to show the size of File.You just need to use file.size in the Object instance. For example, youimage = $('#imagem')[0].files[0];,it means images is the File instance. Now you just need to read the image.sie to know what you want t know. Of curse, you can judge it in background server using PHP or others. And html form can add hidden item named "MAX_FILE_SIZE",but it not easy to know the size through javascript. So the most popular way to do it is using file.size