JSFiddle - React, Tailwind, and code Playground
by Keith Henry
HTML
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/umd/comlink.min.js"></script>
<script id='worker' type='javascript/worker'>
importScripts('https://cdn.jsdelivr.net/npm/[email protected]/dist/umd/comlink.min.js');
function postFiles(files) {
if(!files)
return 0;
const body = new FormData();
for (const f of files)
body.append('files', f, f.name);
const request = new Request('https://example.com', {
method: 'POST',
body,
credentials: 'same-origin'
});
return 1;
}
Comlink.expose(postFiles);
</script>
<input id="fileSelect" type="file" multiple>
JavaScript
const blob = new Blob([document.getElementById('worker').textContent], {type: 'application/javascript'});
const worker = new Worker(window.URL.createObjectURL(blob), {
name: 'Fetch Service'
});
const service = Comlink.wrap(worker);
const fileSelect = document.getElementById('fileSelect');
fileSelect.addEventListener('change', async e => {
const fileList = fileSelect.files;
console.log(fileList);
console.log(await service(fileList));
})