Published
Edited
Nov 10, 2019
Fork of File Input
Insert cell
Insert cell
viewof image = imageInput({
crossOrigin: "anonymous",
initialUrl: "https://gist.githubusercontent.com/mbostock/1db888aa9f6518d86f625d0fe9db22b9/raw/0fe4a0af29c5de8d09fc2b1e9a1bccd50644c417/beastie-boys.jpg"
})
Insert cell
image
Insert cell
viewof data = jsonInput({
initialUrl: "https://gist.githubusercontent.com/mbostock/015ef4a7a8bc67092ea9ebde15f71785/raw/c214e2100bd6b1b4ca0d694711824402f7ad5ce8/points.json"
})
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.
}) {
console.log("Sanity check");
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>`, {accept})}
`;
form.onsubmit = event => {
console.log("Hello kunal");
form.value = load(form.url.value);
form.dispatchEvent(new CustomEvent("input"));
event.preventDefault();
};
form.url.oninput = event => {
event.stopPropagation();
};
form.file.onchange = () => {
console.log("Hey there kunalb");
if (file !== null) URL.revokeObjectURL(file);
file = URL.createObjectURL(form.file.files[0]);
form.value = load(form.url.value = file);
};
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

Purpose-built for displays of data

Observable is your go-to platform for exploring data and creating expressive data visualizations. Use reactive JavaScript notebooks for prototyping and a collaborative canvas for visual data exploration and dashboard creation.
Learn more