Configuring File Upload Components

File and Image Upload Widgets Documentation

We have two widgets, FormFilePicker and FormImagePicker, that provide user-friendly interfaces for uploading files and images.

The code for these widgets can be found in the frontend/src/components directory.

Example: Using FormImagePicker in Profile Page with Formik

Here’s an example of how FormImagePicker is utilized on the profile page for avatar upload, integrated with Formik:

import FormImagePicker from '../components/FormImagePicker';
...
<Formik
  enableReinitialize
  initialValues={initialValues}
  onSubmit={(values) => handleSubmit(values)}
>
  <Form>
    ...
    <Field
      label='Avatar'
      color='info'
      icon={mdiUpload}
      path={'users/avatar'}
      name='avatar'
      id='avatar'
      schema={{
        size: undefined,
        formats: undefined,
      }}
      component={FormImagePicker}
    ></Field>
    ...
  </Form>
</Formik>

FormFilePicker Component

The FormFilePicker component uses several upload services located in the frontend/src/components/Uploaders directory:

  • FilesUploader
  • ImagesUploader
  • UploadService

UploadService Class

The UploadService class is the core class containing functions such as validate, upload, and uploadToServer, which handle file validation and the process of uploading to the server.

Backend File Upload Services

The functionality for uploading, downloading, deleting files either locally or to Google Cloud (GCloud) is implemented in the backend/src/services/file.js file.

Functions for GCloud / local Operations

  • uploadLocal: Uploads a file locally.
  • downloadLocal: Downloads a file locally.
  • initGCloud: Initializes Google Cloud.
  • deleteGCloud: Deletes a file from the cloud.
  • uploadGCloud: Uploads a file to the cloud.
  • downloadGCloud: Downloads a file from the cloud.

File Routes

The routes for file interactions are defined in backend/src/routes/file.js. This file also determines which storage type (local or GCloud) will be used based on the environment.

If the project is running locally, the local storage will be used; if in production, GCloud will be used.

Defining File Routes

An example of how our application sets the path for /api/file in backend/src/index.js

const fileRoutes = require('./routes/file');
...
app.use('/api/file', fileRoutes);
...

Here is how the /download route in backend/src/routes/file.js is set:

router.get('/download', (req, res) => {
  if (process.env.NODE_ENV == 'production') {
    services.downloadGCloud(req, res);
  } else {
    services.downloadLocal(req, res);
  }
});

Configuration Variables

The backend/src/routes/file.js file uses the following variables from the configuration file backend/src/config.js:

  • uploadDir: Path to the local directory for file interactions.
  • gcloud.hash: Your GCloud storage key.
  • config.gcloud.bucket: Name of the GCloud storage bucket where files will be stored.