Skip to content

Scarica un file dai dati ​

Un mondo può mettere nei suoi data report, registrazioni e risultati sotto forma di file. Un file del genere è un oggetto { name, type, url } con il contenuto in url come data URI. Mostralo come un link il cui attributo download fa salvare al browser il file con il suo nome.

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}`;
});
Live, on a fake world
Open

Come funziona ​

name è il nome del file e type il suo tipo MIME ('text/csv', 'application/pdf'). Quando il mondo non ha dato un nome, name è null e la vista ripiega su 'report'. Il link <a href={file.url} download={name}> salva il file invece di aprirlo e non chiede niente alla persona (I download). Un mondo finto dà il file nella stessa forma { name, type, url } dell'esempio.

Vedi anche ​

Il GUI kit di UNaIVERSE, rilasciato con licenza Apache 2.0. Copyright 2024-2026 UNaIVERSE S.r.l.