N
N
Nube2018-03-22 19:47:53
JavaScript
Nube, 2018-03-22 19:47:53

How to send images using websocket js?

I want to send images via websocket, but I'm failing, plus I haven't worked with c js before (
I hope someone has come across such a task.
HTML markup

<div class="frame" id="scene">
        <div class="cardView">
            <input type="file" id="fileElem" multiple="true" accept="image/*" style="display:none" onchange="handleFiles(this.files)" >
            <button id="fileSelect">Download Images</button>
        </div>
        <div id="imgContainer">
            <ul id="img-list"></ul>
        </div>
        <div>
            <button id="btnUploadImage">Отправить на сервер</button>
        </div>
    </div>

These are listeners, images are created first
var fileSelect = document.getElementById("fileSelect"),
    fileElem = document.getElementById("fileElem");

fileSelect.addEventListener("click", function (e) {
    if (fileElem) {
        fileElem.click();
    }
}, false);

//Создаем элементы
function handleFiles(files) {

    var list = document.getElementById("img-list")
    for (var i = 0; i < files.length; i++) {
        var file = files[i];
        var li = document.createElement("li");
        list.appendChild(li);
        var img = document.createElement("img");
        img.src = window.URL.createObjectURL(file);
        img.height = 60;
        img.onload = function () {
            window.URL.revokeObjectURL(this.src);
        }
        li.appendChild(img);
      // Это метод должен был сработать при нажатие на кнопку "отправить на сервер"
        uploadFile(files)
    }
}

Then I loop through the created data and try to transfer it through the socket.
The trick is that I don’t know how to transfer the created objects, so I passed all the data directly in the -handleFiles method above, expecting an error, but the console is silent)
Actually, the method of sending the created images
//Пробежимся по элементам
btnUploadImage.addEventListener("click" ,uploadFile)

function uploadFile(files) {

    for (var i = 0; i < files.length; i++) {
        file = files[i]
        var reader = new FileReader()
        var rawData = new ArrayBuffer();
        reader.onloadend = function (e) {
            rawData = e.target.result;

            var images = rawData
            var data = { query_type:"loadFrame",   data : {images: images}  }
            console.log(data)
            socket.send(JSON.stringify(data))
        }
        reader.readAsArrayBuffer(file);
    }
}

There is no data on the server and the console is silent, so I don't even know where I'm getting the error (except that uploadFile is called from handleFile) . In general, I need your help. Thank you!
ps In theory, I would like to load using the server, for example, as request.FormFile().

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question