Overview
TheuseFileStorage composable provides a simple way to handle file uploads in your Nuxt application. It processes files from HTML file inputs, serializes them with their content as base64 data URLs, and makes them ready to send to your backend API.
Function Signature
Parameters
Configuration options for the file storage behavior.
When
true, automatically clears previously stored files when new files are added. When false, new files are appended to the existing files array.Return Value
A Vue ref containing an array of processed files. Each file includes the original file properties plus the base64-encoded content.
ClientFile Type
An async function to handle file input events. Pass this directly to the
@input event of your file input element. The function:- Accepts an input event containing selected files
- Clears old files if
clearOldFilesistrue - Reads and serializes all files as base64 data URLs
- Returns a promise that resolves when all files are processed
A function to manually clear all files from the
files array.Usage
Basic Example
- Single File Input
- Multiple Files
- Preserve Old Files
Multiple File Input Fields
When working with multiple file input fields, create a separate instance ofuseFileStorage for each input to keep their state isolated.
Waiting for File Processing
ThehandleFileInput function returns a promise, allowing you to wait for file processing to complete:
Notes
All files are read and converted to base64 data URLs automatically. This means the
content property of each file will contain the full file data, which may result in large payloads for big files.Best Practices
-
Single vs Multiple Instances: Create separate
useFileStorageinstances for each file input field to avoid state conflicts. - Memory Considerations: Since files are base64 encoded, they will be roughly 33% larger in memory. Consider file size limits for large uploads.
- Error Handling: Wrap your upload logic in try-catch blocks to handle potential errors during file reading or upload.
- Clear After Upload: Clear files after successful upload to free memory:
See Also
- storeFileLocally - Store uploaded files on the server
- ServerFile Type - Type definition for files received on the server
- ClientFile Type - Type definition for files on the client