Ограничения для управления файлами с помощью JavaScript - PullRequest
0 голосов
/ 05 марта 2019

Прошу прощения за то, что я не хорошо владею английским языком, потому что я не живу в англоязычной стране.

Я студент, и я хочу написать код для шифрования файлов и загрузить этот файл с помощью jquery (на стороне клиента).

Я решил это, но у меня есть некоторые проблемы.

Когда я загружаю файл для шифрования файла большого размера, мой сайт падает.(Мой код будет применен к простой домашней странице.)

Когда я запускаю этот процесс в браузере Firefox или icedragon, я вижу ошибку «переполнение размера выделения».

Можете ли вы сказать мнепочему возникла эта проблема?

Код, который я написал ниже, и ссылочный адрес здесь .

$(function(){

var body = $('body'),
    stage = $('#stage'),
    back = $('a.back');

/* Step 1 */

$('#step1 .encrypt').click(function(){
    body.attr('class', 'encrypt');

    // Go to step 2
    step(2);
});

$('#step1 .decrypt').click(function(){
    body.attr('class', 'decrypt');
    step(2);
});


/* Step 2 */


$('#step2 .button').click(function(){
    // Trigger the file browser dialog
    $(this).parent().find('input').click();
});


// Set up events for the file inputs

var file = null;

$('#step2').on('change', '#encrypt-input', function(e){

    // Has a file been selected?

    if(e.target.files.length!=1){
        alert('Please select a file to encrypt!');
        return false;
    }

    file = e.target.files[0];

    /*if(file.size > 1024*1024*50){
        alert('Please choose files smaller than 50mb, otherwise you may crash your browser. \nThis WARNING is for you.');
        return;
    }*/

    step(3);
});

$('#step2').on('change', '#decrypt-input', function(e){

    if(e.target.files.length!=1){
        alert('Please select a file to decrypt!');
        return false;
    }

    file = e.target.files[0];
    step(3);
});


/* Step 3 */


$('a.button.process').click(function(){

    var input = $(this).parent().find('input[type=password]'),
        a = $('#step4 a.download'),
        password = input.val();

    input.val('');

    if(password.length<5){
        alert('Please choose a longer password!');
        return;
    }

    // The HTML5 FileReader object will allow us to read the
    // contents of the  selected file.

    var reader = new FileReader();

    if(body.hasClass('encrypt')){

        // Encrypt the file!

        reader.onload = function(e){

            // Use the CryptoJS library and the AES cypher to encrypt the
            // contents of the file, held in e.target.result, with the password
            var encrypted = CryptoJS.AES.encrypt(e.target.result, password);


            var encryptedFileArray = [encrypted];
            var blob = 'Blob Data';
            var fileName = file.name + '.encrypted';

            if(window.navigator.msSaveOrOpenBlob) {
                window.navigator.msSaveOrOpenBlob(blob, fileName);
            } else {

                var blobEncrypted = new Blob(encryptedFileArray, { type: 'application/octet-stream' });

                var blobUrl = URL.createObjectURL(blobEncrypted);
                $(a).attr({
                    'download': file.name + '.encrypted',
                    'href': blobUrl
                });
            }

            // The download attribute will cause the contents of the href
            // attribute to be downloaded when clicked. The download attribute
            // also holds the name of the file that is offered for download.
            step(4);
        };

        // This will encode the contents of the file into a data-uri.
        // It will trigger the onload handler above, with the result

        reader.readAsDataURL(file);
    }
    else {

        // Decrypt it!

        reader.onload = function(e){

            var decrypted = CryptoJS.AES.decrypt(e.target.result, password).toString(CryptoJS.enc.Latin1);

            if(!/^data:/.test(decrypted)){
                alert("Invalid pass phrase or file! Please try again.");
                return false;
            }


            var url = decrypted; 
            var userAgent = navigator.userAgent; 
            var filename = file.name.replace('.encrypted',''); 
            var xhr = new XMLHttpRequest(); 

            xhr.responseType = 'blob';
            xhr.onload = function () {
                $(a).attr({
                    'download': filename,
                    'href': window.URL.createObjectURL(xhr.response) // xhr.response is a blob
                });
            };
            xhr.open('GET', url);
            xhr.send();

            step(4);
        };

        reader.readAsText(file);
    }
});


/* The back button */


back.click(function(){

    // Reinitialize the hidden file inputs,
    // so that they don't hold the selection
    // from last time

    $('#step2 input[type=file]').replaceWith(function(){
        return $(this).clone();
    });

    step(1);
});


// Helper function that moves the viewport to the correct step div

function step(i){

    if(i == 1){
        back.fadeOut();
    }
    else{
        back.fadeIn();
    }

    // Move the #stage div. Changing the top property will trigger
    // a css transition on the element. i-1 because we want the
    // steps to start from 1:

    stage.css('top',(-(i-1)*100)+'%');
}

});

1 Ответ

0 голосов
/ 05 марта 2019
xhr.open('GET', url);

вы используете метод GET.возможно лучше использовать POST вместо этого.какой у вас язык на стороне сервера?это PHP?если это PHP, лучше проверить размер загружаемого файла в файле "php.ini".

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...