---
sidebar_position: 4
title: File and Image Upload
slug: rWvXw__Z48Cd1IrHU-QMl
createdAt: Thu Jul 18 2024 05:46:44 GMT+0000 (Coordinated Universal Time)
updatedAt: Fri Jul 19 2024 03:54:30 GMT+0000 (Coordinated Universal Time)
---

# 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

```javascript
const onOversize = (file) => {
	console.log('The file size cannot exceed 30MB');
};
```

### 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

```javascript
function afterRead(file) {
	const formData = new FormData();
	formData.append('file', file.file);

	// Call the upload API
	uploadFile(formData).then(res => {
		if (res.code == 200 && res.data && res.data.length) {
			imageStore.addImage(res.data);
		}
	}).catch(err => {
		showToast('image upload failed');
		console.log(err);
	});
}
```

### 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

```javascript
const uploadFile = async (formData) => {
	const response = await fetch('https://tmp-file.aigic.ai/api/v1/upload?expires=1800&type=image/png', {
		method: 'POST',
		body: formData
	});

	const data = await response.json();
	return data;
};
```

### 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

1. **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.
2. **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.
3. **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

```javascript
// Assuming this is part of a Vue component
onMounted(() => {
	// File input event listener
	document.getElementById('fileInput').addEventListener('change', (event) => {
		const file = event.target.files[0];
		if (file.size > 30 * 1024 * 1024) {
			onOversize(file);
		} else {
			afterRead({ file });
		}
	});
});
```

### 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.
