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

Function sendFileData

tutorials/http/device-dashboard/web_root/components.js:295–330  ·  view source on GitHub ↗
(url, fileName, fileData, chunkSize)

Source from the content-addressed store, hash-verified

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;

Callers 1

onchangeFunction · 0.70

Calls 1

sendChunkFunction · 0.70

Tested by

no test coverage detected