Задать вопрос
nickola105
@nickola105
начинающий

Как передать переменную из одной функции в другую?

Всем привет.
Есть две такие функции.
первая:
function makePhoto() {
    // The width and height of the captured photo. We will set the
    // width to the value defined here, but the height will be
    // calculated based on the aspect ratio of the input stream.

    var width = 320;    // We will scale the photo width to this
    var height = 0;     // This will be computed based on the input stream

    // |streaming| indicates whether or not we're currently streaming
    // video from the camera. Obviously, we start at false.

    var streaming = false;

    // The various HTML elements we need to configure or control. These
    // will be set by the startup() function.

    var video = null;
    var canvas = null;
    var photo = null;
    var startbutton = null;
    var picture = null;
    var useWebcam = document.querySelector('#use-webcam');
    var uploadWrap = document.querySelector('.upload-wrap');
    var applyphoto = document.querySelector('#applytbutton');
    var makePhoto = document.querySelector('.make-photo__wrap');
    var takePhoto = document.querySelector('.take-photo__wrap');
    var morePhoto = document.querySelector('#startbutton');
    var inputPhoto = document.querySelector('#uploadImage');
    
    

    function savephoto() {
            var utf8 = atob(picture),
                array = [];
            //---
            for(var i = 0; i < utf8.length; i++)
                array.push(utf8.charCodeAt(i));
            var myBlob = new Blob([new Uint8Array(array)], {type: 'image/png'});
            var file = new File([myBlob], 'user-photo')
            inputPhoto.files[0] = file;
            console.log(inputPhoto.files[0]);
    }
    /* take photo with dragDropLoad begin */ 
    (function dragDropLoad() {
        var dropbox;
        dropbox = document.querySelector('#dropbox');

        dropbox.addEventListener('dragenter', dragenter, false);
        dropbox.addEventListener('dragover', dragover, false);
        dropbox.addEventListener('drop', drop, false);

        function dragenter(e) {
            e.stopPropagation();
            e.preventDefault();
        }

        function dragover(e) {
            e.stopPropagation();
            e.preventDefault();
        }

        function  drop(e) {
            e.stopPropagation();
            e.preventDefault();

            var dt = e.dataTransfer;
            var file = dt.files[0];
        if (file) {
            createimage(file);
            userPicture = file;
        }

        }
        function createimage(file) {
            var imgUser = document.querySelector('.output-input img');
            var uploadWrap = document.querySelector('.upload-wrap');
            uploadWrap.style.display = 'none';
            imgUser.style.display = 'block';
            imgUser.src = window.URL.createObjectURL(file);
            imgUser.onload = function() {
                window.URL.revokeObjectURL(this.src);

            }
        }
    }());
    /* take photo with dragDropLoad end */ 
    /*take photo whith input type file*/
    (function inputFile() {
        var picture;
        var output = document.querySelector('.output-input img');
        var uploadField = document.querySelector('.upload-wrap');
        inputPhoto.addEventListener('change', handleFiles, false);
        function handleFiles() {
            if( this.files && this.files[0] ) {
                    const src = "/images/" + this.files[0].name;

                    output.setAttribute("src", window.URL.createObjectURL(this.files[0]));
                    uploadField.style.display = "none";
                    output.style.display = "block";
                }
        }
    })();
    applyphoto.addEventListener('click', savephoto, false);
    useWebcam.addEventListener('click', startup, false);
    morePhoto.addEventListener('click', startup, false);
    // Set up our event listener to run the startup process
};

и вторая:
(function () {
    
  var form = function(option) {
      
        var initCalled = false;
        var elsForm = document.querySelector(option.name);
        var uri = option.uri;
        var file = userPicture;
        //console.log(userPicture);
    
        var init = function() {
            if (!initCalled) {
                initCalled = true;
                handleSubmit(elsForm);
            }
        };

        function toJSONString( form ) {
            var obj = {};
            var elements = form.querySelectorAll( "input, select, textarea" );
            console.log(elements);
		    for( var i = 0; i < elements.length; ++i ) {
			    var element = elements[i];
                var name = element.name;
                if (name && element.type !== "file") {
                    if (element.type === "radio" && element.checked){
                        obj[ name ] = element.value;
                    } else if (element.type === "chekbox" && element.checked) {        
                        obj[ name ] = element.value;
                    } else {
                        obj[ name ] = element.value;
                    }
                } else {
                    console.log(element.files[0]);
                    obj[name] = element.files[0];   
                }    
			    // var value = element.value;   
			    // if( name ) {
                //     if (element.type === "radio" && element.checked){
                //         obj[ name ] = value;
                //     } else if (element.type !== "radio") {        
                //         obj[ name ] = value;
                //     }
			    // }
		    }          
		    return JSON.stringify( obj );
	    }

        var handleSubmit = function(elsForm) {
            elsForm.addEventListener("submit", function( e ) {
                e.preventDefault();
                var json = toJSONString( this );
                console.log(this);    
                sendForm(json, uri);    
		    }, false)
        };

        function sendForm(data, uri) {
            
            var uri = uri;
            console.log(data);
            var xhr = new XMLHttpRequest();
            var fd = new FormData();

            xhr.open("POST", uri, true);
            xhr.onreadystatechange = function() {
                if (xhr.readyState == 4 && xhr.status == 200) {
                    alert(xhr.responseText);
                }
            };
            fd.append('dataform', data);
            
            xhr.send(fd);
        };
  
        return {
            init: init,
            sendForm: sendForm
        };
}
    window.form = form;
})();


Возникло два вопроса:
1. Как передать файл из функций savePhoto() и dragDropLoad() первой функции во вторую где есть запрос на сервер?
2. Почему при отправке формы в объект не записывается element.files[0] в консоль ошибка: Uncaught TypeError: Cannot read property '0' of null?
  • Вопрос задан
  • 237 просмотров
Подписаться 1 Оценить Комментировать
Пригласить эксперта
Ответы на вопрос 1
Stalker_RED
@Stalker_RED
1. У вас большинство функций обернуты в само-вызываемые (self-invoking) выражения
(код)()
Обычно это специально делается, чтоб снаружи к этой функции было сложнее достучаться. Вам придется либо разобраться зачем это сделано, и можно ли пересмотреть использование такого подхода, либо нагородить кучу костылей.

2. Скорее всего в процессе работы что-то идет не так, и в какой-то момент происходит попытка прочитать значение element.files[0] у элемента, у которого вообще нет .files. Проще всего посмотреть в отладчике, который встроен в DevTools браузера.
Ответ написан
Комментировать
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Похожие вопросы