Answer the question
In order to leave comments, you need to log in
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>
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)
}
}
//Пробежимся по элементам
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);
}
}
Answer the question
In order to leave comments, you need to log in
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question