Send a file
world.send({ file, text }) sends a file on behalf of the person with an optional text. The file can be a File from a file input or a drop event, a Blob or a { name, type, url } object with a base64 data URI and must not exceed 20 MB. Above that limit send rejects with the code 'too-big' and sends nothing. In the example you either pick a file and press Send or press 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}` : '';
});How it works
<input type="file">puts the chosen files ininput.filesandsendtakes theFileininput.files[0]as it is. Theacceptattribute (accept=".pdf,image/*") restricts the picker to some kinds of file.- Like a text, a file makes
sendresolve with'sent','failed'or'not-allowed'. When the call cannot even start,sendrejects with'too-big'for a file over 20 MB before anything leaves or with'not-allowed-verb'in a webapp that predates file sending. 'sent'means that the world received the file and says nothing about who reads it. Only the agents of the world with a file input read it and the others ignore it without an error.- One message carries one attachment and a call to
sendwith bothimageandfileresolves'failed'without sending anything. Send the two in separate messages. - The message of the person keeps the name of the file in
message.files. After the webapp reloads, its content is gone andurlisnull(Show the files of a message). - In the example the fake world reads the name and type of the file from
message.filesin itsonMessageand replies with them.
See also
send- FileButton: a ready button that picks a file and sends it.
- Show the files of a message
- Send a photo from the camera