For uploaded files, different preview content can be displayed in the frontend interface based on different file types. The file manager's attachment field has built-in browser-based (embedded in iframe) file preview, which supports most file formats (images, videos, audio, and PDF, etc.) to be previewed directly in the browser. When the file format does not support browser preview, or when there are special preview interaction needs, you can implement it by extending preview components based on file types.
For example, if you want to extend a carousel switching component for image type files, you can use the following code:
Where attachmentFileTypes is an entry object provided in the @tachybase/client package for extending file types. Use its add method to extend a file type description object.
Each file type must implement a match() method to check if the file type meets the requirements. In the example, the method provided by the mime-match package is used to detect the file's mimetype property. If it matches the image/* type, it is considered the file type to be processed. If the match is unsuccessful, it will fall back to the built-in type handling.
The Previewer property on the type description object is the component used for previewing. When the file type matches, this component will be rendered for preview. It is usually recommended to use a modal-type component as the base container (such as <Modal />, etc.), and then place the preview and interactive content inside that component to implement the preview functionality.
attachmentFileTypesattachmentFileTypes is a global instance, imported from @tachybase/client:
attachmentFileTypes.add()Register a new file type description object with the file type registry. The description object type is AttachmentFileType.
AttachmentFileTypematch()File format matching method.
The passed parameter file is the data object of the uploaded file, containing relevant properties that can be used for type determination:
mimetype: mimetype descriptionextname: file extension, including "."path: relative path where the file is storedurl: file URLThe return value is of type boolean, indicating the result of whether it matches.
PreviewerA React component for previewing files.
The Props parameters passed in are:
index: index of the file in the attachment listlist: attachment listonSwitchIndex: method for switching the indexWhere onSwitchIndex can be passed any index value in the list to switch to another file. If null is used as a parameter to switch, the preview component will be closed directly.