< JavaScript

JavaScript - Fájlfeltöltés

Szerző: Sallai András

Copyright © Sallai András, 2022

Licenc: CC Attribution-Share Alike 4.0 International

Web: https://szit.hu

FileReader konstruktor

Weblap

<input type="file" accept="image/jpg, image/png" id="imageup"> <div id="imageBox"></div>

Script

const imageupElem = document.querySelector('#imageup'); const imageBox = document.querySelector('#imageBox'); var uploadedImage = ''; imageupElem.addEventListener('change', () => { const fileReader = new FileReader(); fileReader.addEventListener('load', () => { uploadedImage = fileReader.result; imageBox.style.backgroundImage = `url(${uploadedImage})`; }); fileReader.readAsDataURL(imageupElem.files[0]); });

Törlés

File típusú input elem tartalmának törlése:

document.querySelector('#imageup').value = '';

Átadás REST API számára

var imageupElem = document.querySelector('#imageup'); var saveButton = document.querySelector('#saveButton'); var host = 'http://localhost:8000/api/'; const saveImage = () => { const files = imageupElem.files; const formData = new FormData(); formData.append('file', files[0]); let endpoint = 'imageup'; let url = host + endpoint; fetch(url, { method: 'post', body: formData }) .then(response => response.json()) .then(result => { console.log(result); }) .catch(err => { console.log(err); }) ; } saveButton.addEventListener('click', () => { saveImage(); })

Link

https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch (2022)