formio / formio.js

JavaScript powered Forms with JSON Form Builder
https://formio.github.io/formio.js
MIT License
1.83k stars 1.04k forks source link

custom file component #5606

Open faezeh1378 opened 1 month ago

faezeh1378 commented 1 month ago

Hello I want to create a custom file component in which I can have more than one url address and I can use my own token and request header to access those addresses. for example authorization: Bearer ${window.localStorage.getItem('token')} How can I do this? i use formiojs@4.14.13 Thanks

GMacAussie commented 1 month ago

If I am correct thinking what you are trying to do, here are some things we did:

  1. We added the ability at runtime to update the File component's url based off passed data, as our different form types have different endpoints. We do this 'fixup' prior the form creation;
  2. We implemented our own custom component subclassed from the File component and registered it for the File component type, and implemented:
    • override for the upload API because iOS when using camera capture does not create unique filename (always image.jpg) which causes multi-file issues. The code is really just a copy of the native File component upload method with that filename check;
    • override for the getFile method to retrieve the file via our API which uses a Bearer token;
  3. We implemented our own custom URL Storage Provider class, and implemented the uploadFile, deleteFile and downloadFile methods to hit our API correctly. This URL Storage Provider is used to override the Providers.providers.storage.url entry.
  4. In the form builder, we hide all API and storage provider selection and force set it to the URL provider.

We did this via monkey patching which is not great; we use Angular 16 however the type definitions in Formio 14.X leave something to be desired, and monkey patching was easier (!). I think Formio 5.X will address type definitions.

The above works fine for an browser app with a separate API server (handled by your own code). Issues we ran into:

  1. Multiple simultatenous device use each doing there own image thing. This is tricky - we did backend sync and auto save on image upload/delete as a workaround;
  2. Users switching off devices after uploading/deleting an image but BEFORE the auto-save kicks in. Force immediate save per above works around this.

Sorry for the long reply. Use the existing File component and URL Storage Provider classes of Formio as your templates.