Invia un file
world.send({ file, text }) invia un file a nome della persona con un testo facoltativo. Il file può essere un File preso da un input di tipo file o da un evento drop, un Blob o un oggetto { name, type, url } con un data URI base64 e non può superare i 20 MB. Oltre questo limite send viene rifiutata con il codice 'too-big' e non invia niente. Nell'esempio puoi scegliere un file e premere Send oppure premere Send a sample file.
jsx
import { useState } from 'react';
import { useWorld } from './useWorld.js';
// A fake help desk to build with. It says which file it got.
const desk = {
name: 'Help desk',
onMessage: (message) => {
// The file the person sent is in `message.files`, with its name, type and data URI.
const file = message.files?.[0];
return file ? `Got ${file.name} (${file.type}).` : 'Send me a file.';
},
};
// A small file to try with, made of its name, its type and its content ("Hello, world!") as a base64 data URI.
const SAMPLE = { name: 'notes.txt', type: 'text/plain', url: 'data:text/plain;base64,SGVsbG8sIHdvcmxkIQ==' };
export default function App() {
// While building: the fake world. In the webapp: useWorld()
const { world, error } = useWorld({ fake: { world: desk } });
const [file, setFile] = useState(null);
const [note, setNote] = useState('');
if (error) return <p>Could not connect ({error.code}).</p>;
if (!world) return <p>Connecting…</p>;
async function sendFile(chosen) {
try {
// send() takes a File, a Blob, or { name, type, url } of up to 20 MB, with words if you like.
const result = await world.send({ file: chosen });
setNote(result === 'sent' ? 'Sent.' : `Not sent (${result}).`);
} catch (error) {
// Over 20 MB, send() fails with the code 'too-big', and nothing is sent.
setNote(error.code === 'too-big' ? 'This file is over 20 MB: pick a smaller one.' : `Not sent (${error.code}).`);
}
}
const last = world.messages.filter((message) => !message.fromMe).at(-1);
return (
<>
<label>
File{' '}
{/* The file the person picked is a File, and send() takes it as it is. */}
<input type="file" onChange={(event) => setFile(event.target.files[0] ?? null)} />
</label>
<button onClick={() => (file ? sendFile(file) : setNote('Pick a file first.'))} disabled={!world.canSend}>Send</button>
<button onClick={() => sendFile(SAMPLE)} disabled={!world.canSend}>Send a sample file</button>
<p>{note}</p>
<p>{last ? `${last.from}: ${last.text}` : ''}</p>
</>
);
}js
import { connectToHost } from '@unaiverse/gui-kit';
// A fake help desk to build with. It says which file it got.
const desk = {
name: 'Help desk',
onMessage: (message) => {
// The file the person sent is in `message.files`, with its name, type and data URI.
const file = message.files?.[0];
return file ? `Got ${file.name} (${file.type}).` : 'Send me a file.';
},
};
// A small file to try with, made of its name, its type and its content ("Hello, world!") as a base64 data URI.
const SAMPLE = { name: 'notes.txt', type: 'text/plain', url: 'data:text/plain;base64,SGVsbG8sIHdvcmxkIQ==' };
// While building: the fake world. In the webapp: const world = await connectToHost();
const world = await connectToHost({ fake: { world: desk } });
const label = document.createElement('label');
label.textContent = 'File ';
const input = document.createElement('input');
input.type = 'file';
label.append(input);
const sendButton = document.createElement('button');
sendButton.textContent = 'Send';
const sampleButton = document.createElement('button');
sampleButton.textContent = 'Send a sample file';
const note = document.createElement('p');
const answer = document.createElement('p');
document.body.append(label, sendButton, sampleButton, note, answer);
async function sendFile(file) {
try {
// send() takes a File, a Blob, or { name, type, url } of up to 20 MB, with words if you like.
const result = await world.send({ file });
note.textContent = result === 'sent' ? 'Sent.' : `Not sent (${result}).`;
} catch (error) {
// Over 20 MB, send() fails with the code 'too-big', and nothing is sent.
note.textContent = error.code === 'too-big' ? 'This file is over 20 MB: pick a smaller one.' : `Not sent (${error.code}).`;
}
}
sendButton.onclick = () => {
// The file the person picked is a File, and send() takes it as it is.
if (input.files.length) sendFile(input.files[0]);
else note.textContent = 'Pick a file first.';
};
sampleButton.onclick = () => sendFile(SAMPLE);
// Called at once, then after every change of the world.
world.subscribe((node) => {
sendButton.disabled = !node.canSend;
sampleButton.disabled = !node.canSend;
const last = node.messages.filter((message) => !message.fromMe).at(-1);
answer.textContent = last ? `${last.from}: ${last.text}` : '';
});Come funziona
<input type="file">mette i file scelti ininput.filesesendprende così com'è ilFileininput.files[0]. L'attributoaccept(accept=".pdf,image/*") limita il selettore ad alcuni tipi di file.- Come per un testo, con un file
sendsi risolve con'sent','failed'o'not-allowed'. Quando la chiamata non può nemmeno partire,sendviene rifiutata con'too-big'per un file oltre i 20 MB prima che parta qualsiasi cosa oppure con'not-allowed-verb'in una webapp precedente all'invio dei file. 'sent'vuol dire che il mondo ha ricevuto il file e non dice niente su chi lo legge. Lo leggono solo gli agenti del mondo con un input di tipo file e gli altri lo ignorano senza errori.- Un messaggio porta un solo allegato e una chiamata a
sendconimageefileinsieme si risolve quindi con'failed'senza inviare niente. Invia le due cose in messaggi separati. - Il messaggio della persona conserva il nome del file in
message.files. Dopo un ricaricamento della webapp il contenuto del file non c'è più e il suourlènull(Mostra i file di un messaggio). - Nell'esempio il mondo finto legge nome e tipo del file da
message.filesnel suoonMessagee risponde con questi due valori.
Vedi anche
send- FileButton: un pulsante pronto che sceglie un file e lo invia.
- Mostra i file di un messaggio
- Invia una foto dalla fotocamera