Published
Edited
Feb 9, 2020
Fork of File Input
Importers
1 star
Insert cell
Insert cell
viewof image = imageInput({
crossOrigin: "anonymous",
initialUrl: await FileAttachment("beastie-boys.jpg").url()
})
Insert cell
image
Insert cell
viewof data = fileInput({
initialUrl: await FileAttachment("points.json").url()
})
Insert cell
data
Insert cell
Insert cell
function fileInput({
initialUrl, // e.g., "https://example.com/file.txt"
accept, // e.g., ".txt,.md"
load = value => value // A function to specify which value is exposed.
}) {
let file = null;
const form = html`<form>
${Object.assign(html`<input name=url>`, {value: initialUrl})}
<button>Submit</button>
${Object.assign(html`<input data-type=file name=file type=file multiple=true>`, {accept})}
`;
form.onsubmit = event => {
form.value = load(form.url.value);
form.dispatchEvent(new CustomEvent("input"));
event.preventDefault();
};
form.url.oninput = event => {
event.stopPropagation();
};
form.file.oninput = () => {
if (file !== null) URL.revokeObjectURL(file);
console.log('files', form.file.files)

form.value =[];
const len = form.file.files.length
for(let i=0; i<len; i++){
file = URL.createObjectURL(form.file.files[i]);
console.log(file);
form.value.push({file:load(form.url.value = file)
, filename:form.file.files[i].name
});
};
};
if (initialUrl !== undefined) {
form.value = load(initialUrl);
}
return form;
}
Insert cell
function imageInput({initialUrl, width, height, crossOrigin, accept = ".png,.jpg,.gif,.webp"}) {
return fileInput({
initialUrl,
accept,
load(url) {
return new Promise((resolve, reject) => {
const image = new Image;
image.style.display = "block";
if (width !== undefined) image.width = width;
if (height !== undefined) image.height = height;
if (crossOrigin !== undefined) image.crossOrigin = crossOrigin;
image.onload = () => resolve(image);
image.onerror = reject;
image.src = url;
});
}
});
}
Insert cell
function jsonInput({initialUrl, init, accept = ".json"}) {
return fileInput({
initialUrl,
accept,
load(url) {
return fetch(url, init).then(response => {
if (!response.ok) throw new Error(response.status + " " + response.statusText);
return response.json();
});
}
});
}
Insert cell

One platform to build and deploy the best data apps

Experiment and prototype by building visualizations in live JavaScript notebooks. Collaborate with your team and decide which concepts to build out.
Use Observable Framework to build data apps locally. Use data loaders to build in any language or library, including Python, SQL, and R.
Seamlessly deploy to Observable. Test before you ship, use automatic deploy-on-commit, and ensure your projects are always up-to-date.
Learn more