Uploading Files
In this section, we will guide you through the process of uploading a file to a Store. This process involves both uploading the file content and managing its associated meta data. Storing meta data, such as the file's name, and type, allows for easier identification and retrieval of files when needed.
We highly recommend storing the file's meta data along with the file content to make it easier to manage and interact with the uploaded file in the future.
const encoder = new TextEncoder();
const file = FormData.get('file');
const fileId = await Endpoint.connection().context(CONTEXT_ID).store(STORE_ID).uploadFile({
file,
privateMeta: encoder.encode(JSON.stringify({name: file.name, type: file.type, lastModified: file.lastModified}))
publicMeta: new Uint8Array()
})
Streaming
For larger files or scenarios where you need more control over the upload process (e.g. managing upload progress, pausing, or canceling uploads), we recommend using streaming. Streaming allows you to upload the file in chunks, enabling better interactivity, monitoring, and control.
Streaming is especially useful when:
- You need to upload large files and a single upload might take a long time;
- You need the ability to cancel the upload in the middle of the process.
const encoder = new TextEncoder();
const file = FormData.get('file') as File;
const streamer = await Endpoint.connection()
.context('CONTEXT_ID')
.store('STORE_ID')
.streamFile({
file,
privateMeta: encoder.encode(
JSON.stringify({
name: file.name,
type: file.type,
lastModified: file.lastModified
})
),
publicMeta: new Uint8Array()
});
try {
while (await streamer.sendNextChunk()) {
console.log(streamer.progress);
}
} catch {
streamer.abort();
}
const fileId = await streamer.close();
Notes
- Meta data: helps you identify files later on by storing additional information about them. You can use both private meta data (which might contain sensitive or internal data) and public meta data (which can be shared publicly).
- Error Handling: During the streaming process, it's important to handle potential errors, such as network interruptions, by using try-catch blocks and the ability to abort the upload.
- Progress Monitoring: Streaming enables you to monitor the progress of the file upload, allowing you to display the current upload percentage to the user.