MCPcopy Create free account
hub / github.com/cesanta/mongoose / UploadFileButton

Function UploadFileButton

tutorials/http/device-dashboard/web_root/components.js:288–356  ·  view source on GitHub ↗
(props)

Source from the content-addressed store, hash-verified

286};
287
288export function UploadFileButton(props) {
289 const [upload, setUpload] = useState(null); // Upload promise
290 const [status, setStatus] = useState(''); // Current upload status
291 const btn = useRef(null);
292 const input = useRef(null);
293
294 // Send a large file chunk by chunk
295 const sendFileData = function(url, fileName, fileData, chunkSize) {
296 return new Promise(function(resolve, reject) {
297 const finish = ok => {
298 setUpload(null);
299 const res = props.onupload ? props.onupload(ok, fileName, fileData.length) : null;
300 if (res && typeof (res.catch) === 'function') {
301 res.catch(() => false).then(() => ok ? resolve() : reject());
302 } else {
303 ok ? resolve() : reject();
304 }
305 };
306 const sendChunk = function(offset) {
307 var chunk = fileData.subarray(offset, offset + chunkSize) || '';
308 var opts = {method: 'POST', body: chunk};
309 var fullUrl = url + '?offset=' + offset +
310 '&total=' + fileData.length +
311 '&name=' + encodeURIComponent(fileName);
312 var ok;
313 setStatus('Uploading ' + fileName + ', bytes ' + offset + '..' +
314 (offset + chunk.length) + ' of ' + fileData.length);
315 fetch(fullUrl, opts)
316 .then(function(res) {
317 if (res.ok && chunk.length > 0) sendChunk(offset + chunk.length);
318 ok = res.ok;
319 return res.text();
320 })
321 .then(function(text) {
322 if (!ok) setStatus('Error: ' + text), finish(ok); // Fail
323 if (chunk.length > 0) return; // More chunks to send
324 setStatus(x => x + '. Done, resetting device...');
325 finish(ok); // All chunks sent
326 });
327 };
328 sendChunk(0);
329 });
330 };
331
332 const onchange = function(ev) {
333 if (!ev.target.files[0]) return;
334 let r = new FileReader(), f = ev.target.files[0];
335 r.readAsArrayBuffer(f);
336 r.onload = function() {
337 setUpload(sendFileData(props.url, f.name, new Uint8Array(r.result), 2048));
338 ev.target.value = '';
339 ev.preventDefault();
340 btn && btn.current.base.click();
341 };
342 };
343
344 const onclick = function(ev) {
345 let fn; setUpload(x => fn = x);

Callers

nothing calls this directly

Calls

no outgoing calls

Tested by

no test coverage detected