Skip to content

Commit

Permalink
File transfer in base64 over metacom
Browse files Browse the repository at this point in the history
PR-URL: metarhia#39
  • Loading branch information
tshemsedinov committed Sep 16, 2020
1 parent e527693 commit 66a74e1
Show file tree
Hide file tree
Showing 2 changed files with 61 additions and 2 deletions.
9 changes: 9 additions & 0 deletions application/api/example.1/uploadFile.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
async ({ name, data }) => {
const buffer = Buffer.from(data, 'base64');
const tmpPath = 'application/tmp';
const filePath = node.path.join(tmpPath, name);
if (filePath.startsWith(tmpPath)) {
await node.fsp.writeFile(filePath, buffer);
}
return { uploaded: data.length };
};
54 changes: 52 additions & 2 deletions application/static/console.js
Original file line number Diff line number Diff line change
Expand Up @@ -229,10 +229,60 @@ document.onkeypress = event => {
}
};

const blobToBase64 = blob => {
const reader = new FileReader();
reader.readAsDataURL(blob);
return new Promise(resolve => {
reader.onloadend = () => {
resolve(reader.result);
};
});
};

const uploadFile = (file, done) => {
blobToBase64(file)
.then(url => {
const data = url.substring(url.indexOf(',') + 1);
api.example.uploadFile({ name: file.name, data }).then(done);
});
};

const upload = () => {
const element = document.createElement('form');
element.style.visibility = 'hidden';
element.innerHTML = '<input id="fileSelect" type="file" multiple />';
document.body.appendChild(element);
const fileSelect = document.getElementById('fileSelect');
fileSelect.click();
fileSelect.onchange = () => {
const files = Array.from(fileSelect.files);
print('Uploading ' + files.length + ' file(s)');
files.sort((a, b) => a.size - b.size);
let i = 0;
const uploadNext = () => {
const file = files[i];
uploadFile(file, () => {
print(`name: ${file.name}, size: ${file.size} done`);
i++;
if (i < files.length) {
return uploadNext();
}
document.body.removeChild(element);
commandLoop();
});
};
uploadNext();
};
};

const exec = async line => {
const args = line.split(' ');
const data = await api.cms.content(args);
print(data);
if (args[0] === 'upload') {
upload();
} else {
const data = await api.cms.content(args);
print(data);
}
commandLoop();
};

Expand Down

0 comments on commit 66a74e1

Please sign in to comment.