File and Image Upload
This documentation provides a detailed explanation of how to handle file and image uploads in your application, including file size validation, preparing form data, and interacting with the upload API.
Function: onOversize
Description
The onOversize function checks if the uploaded file exceeds the maximum allowed size and displays a notification if it does.
Code
Usage
- Parameters:
- file: The file object to be checked.
- Behavior:
- Displays a toast notification if the file size exceeds 30MB.
Function: afterRead
Description
The afterRead function processes the file after it has been read, prepares it for upload, and calls the uploadFile function to handle the actual upload.
Code
Usage
- Parameters:
- file: The file object that has been read.
- Behavior:
- Creates a FormData object and appends the file.
- Calls the uploadFile function to upload the file.
- Adds the uploaded image to imageStore if the upload is successful.
- Displays an error toast if the upload fails.
Function: uploadFile
Description
The uploadFile function uploads the given file to the server using a POST request and returns the response.
Code
Usage
- Parameters:
- formData: The FormData object containing the file to be uploaded.
- Behavior:
- Sends a POST request to the upload API endpoint.
- Returns the response data.
Workflow
- File Selection and Validation:
- The user selects a file.
- The onOversize function checks if the file size exceeds 30MB. If it does, a toast notification is shown.
- File Upload:
- The afterRead function is called with the selected file.
- A FormData object is created and the file is appended to it.
- The uploadFile function is called with the FormData object.
- API Interaction:
- The uploadFile function sends a POST request to the upload API endpoint.
- If the upload is successful, the response data is added to the imageStore.
- If the upload fails, a toast notification is shown and the error is logged.
Example Usage
Notes
- Ensure the API endpoint (https://tmp-file.aigic.ai/api/v1/upload) and parameters (expires and type) are correctly set as per your backend requirements.
- Handle exceptions and errors gracefully to provide a good user experience.
- Customize the toast notifications as needed for your application.
By following this documentation, developers can easily integrate file and image upload functionality into their applications, ensuring proper validation, handling, and error management.