entrance-exam/app/javascript/image_input.js

35 lines
1.5 KiB
JavaScript

const csrfToken = document.querySelector("[name='csrf-token']").content
export default function initImageQuestions() {
document.querySelectorAll('[data-behaviour="question_image_input"]').forEach((input) => {
const submitUrl = input.dataset.submitUrl
input.addEventListener('change', () => {
const file = input.files[0];
const fileReader = new FileReader();
fileReader.onload = (ev) => {
fetch(submitUrl, {
method: 'PUT',
headers: {
"x-csrf-token": csrfToken,
"content-type": "application/json",
},
body: JSON.stringify({
filename: file.name,
mimetype: file.type,
data: ev.target.result.replace(/^data:[a-zA-Z0-9!#$%^&\\*_\-+{}|'.`~]+\/[a-zA-Z0-9!#$%^&\\*_\-+{}|'.`~]+;base64,/, ""),
})
})
}
fileReader.readAsDataURL(file);
const preview = document.querySelector(`#${input.id}_preview`)
while (preview.firstChild) {
preview.removeChild(preview.firstChild)
}
const previewImage = document.createElement("img")
previewImage.src = URL.createObjectURL(file)
previewImage.alt = previewImage.title = file.name
preview.appendChild(previewImage)
})
})
}