Download a file from data
A world can put reports, recordings and results in its data as files. Such a file is a { name, type, url } object whose url holds the content as a data URI. Render it as a link whose download attribute makes the browser save the file under its name.
jsx
import { useWorld } from './useWorld.js';
// A file in `data` is { name, type, url }: its name (or null), its type, and its content as a data URI.
const csv = 'day,visitors\nMonday,120\nTuesday,98\nWednesday,143\n';
const visits = {
name: 'Museum',
data: { report: { name: 'visits.csv', type: 'text/csv', url: `data:text/csv;charset=utf-8,${encodeURIComponent(csv)}` } },
};
export default function App() {
// While building: the fake world. In the webapp: useWorld()
const { world, error } = useWorld({ fake: { world: visits } });
if (error) return <p>Could not connect ({error.code}).</p>;
if (!world) return <p>Connecting…</p>;
const file = world.data.report;
if (!file) return <><h2>{world.name}</h2><p>No report yet.</p></>;
const name = file.name ?? 'report';
return (
<>
<h2>{world.name}</h2>
{/* `download` saves the file under its name, instead of opening it. */}
<a href={file.url} download={name}>Download {name}</a>
<p>Type: {file.type}</p>
</>
);
}js
import { connectToHost } from '@unaiverse/gui-kit';
// A file in `data` is { name, type, url }: its name (or null), its type, and its content as a data URI.
const csv = 'day,visitors\nMonday,120\nTuesday,98\nWednesday,143\n';
const visits = {
name: 'Museum',
data: { report: { name: 'visits.csv', type: 'text/csv', url: `data:text/csv;charset=utf-8,${encodeURIComponent(csv)}` } },
};
// While building: the fake world. In the webapp: const world = await connectToHost();
const world = await connectToHost({ fake: { world: visits } });
const title = document.createElement('h2');
const link = document.createElement('a');
const type = document.createElement('p');
document.body.append(title, link, type);
world.subscribe((node) => {
title.textContent = node.name;
const file = node.data.report;
link.hidden = !file;
if (!file) {
type.textContent = 'No report yet.';
return;
}
const name = file.name ?? 'report';
link.href = file.url;
// `download` saves the file under its name, instead of opening it.
link.download = name;
link.textContent = `Download ${name}`;
type.textContent = `Type: ${file.type}`;
});How it works
name is the file name and type its MIME type ('text/csv', 'application/pdf'). When the world gave no name, name is null and the view falls back to 'report'. The link <a href={file.url} download={name}> saves the file instead of opening it and asks the person nothing (Downloads). A fake world gives the file in the same { name, type, url } shape as in the example.
See also
- FileList: a list of files from data.
- The camera and the rest of the browser: what your view may do in the webapp.
- The data of the world.