简体   繁体   English

Javascript-如何设置要上传图片的大小限制,上限为2mb。 脚本已包含

[英]Javascript - how to set the size limit of the picture to be uploaded up to 2mb. Script already included

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. 我想设置上传图片的上限为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. 如果图片小于2mb,它将沿着正常路径前进并被上传;如果图片大于2mb,则弹出窗口将显示错误消息。 Can anybody help me in how to do this with javascript alone? 有人可以帮助我如何单独使用javascript吗? 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. 请按照以下脚本操作,只需要帮助我设置图像的大小限制即可,否则,没有人可以上传5GB图像并使服务器超载。

        // 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. 我不是javascript编码器。 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 SOmeone请在允许上传之前将代码的一部分写在验证文件大小的地方,请

File objcet offer a property to show the size of File.You just need to use file.size in the Object instance. File objcet提供了一个属性来显示File的大小。您只需要在Object实例中使​​用file.size即可。 For example, you image = $('#imagem')[0].files[0]; 例如,您image = $('#imagem')[0].files[0]; ,it means images is the File instance. ,它表示图像是File实例。 Now you just need to read the image.sie to know what you want t know. 现在,您只需要阅读image.sie即可知道您不想要的内容。 Of curse, you can judge it in background server using PHP or others. 当然,您可以使用PHP或其他工具在后台服务器中对其进行判断。 And html form can add hidden item named "MAX_FILE_SIZE",but it not easy to know the size through javascript. 而且html表单可以添加名为“ MAX_FILE_SIZE”的隐藏项,但通过javascript很难知道其大小。 So the most popular way to do it is using file.size 因此,最流行的方法是使用file.size

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM