### Install and Run React File Manager Frontend Source: https://github.com/saifullah-dev/react-file-manager/blob/main/README.md Commands to set up and start the frontend development server for the React File Manager. After installation, the application will be accessible at http://localhost:5173. ```bash cd frontend npm i npm run dev ``` -------------------------------- ### Install and Run React File Manager Backend Source: https://github.com/saifullah-dev/react-file-manager/blob/main/README.md Commands to set up and start the backend development server for the React File Manager. The backend server, typically handling file system changes, will run on http://localhost:3000. ```bash cd backend npm i npm run devStart ``` -------------------------------- ### Start Backend Server for File Rename Testing Source: https://github.com/saifullah-dev/react-file-manager/blob/main/backend/Readme.md This alternative start command is recommended when testing file rename functionality to avoid potential permission-related issues. It starts the backend server on http://localhost:3000. ```bash npm run start ``` -------------------------------- ### Install Backend Dependencies with npm Source: https://github.com/saifullah-dev/react-file-manager/blob/main/backend/Readme.md After navigating to the backend directory, this command installs all necessary Node.js dependencies listed in the package.json file. This is a crucial step before running the backend server. ```bash npm i ``` -------------------------------- ### Install React File Manager using npm Source: https://github.com/saifullah-dev/react-file-manager/blob/main/README.md This command installs the React File Manager package and its dependencies using npm. Ensure you have Node.js and npm installed on your system. ```bash npm i @cubone/react-file-manager ``` -------------------------------- ### Start Backend Development Server with Nodemon Source: https://github.com/saifullah-dev/react-file-manager/blob/main/backend/Readme.md This command starts the backend development server using npm. It utilizes nodemon for automatic server restarts upon code changes, enhancing the development workflow. Ensure .env file is configured. ```bash npm run devStart ``` -------------------------------- ### React File Manager Component Setup and Event Handlers Source: https://context7.com/saifullah-dev/react-file-manager/llms.txt Demonstrates the setup of the FileManager component in a React application. It includes fetching initial files, handling folder creation, file uploads, renaming, deletion, copy/move operations, downloads, and error/selection events. The component relies on the 'axios' library for API communication. ```jsx import { useState, useEffect } from "react"; import { FileManager } from "@cubone/react-file-manager"; import "@cubone/react-file-manager/dist/style.css"; import axios from "axios"; function App() { const [files, setFiles] = useState([]); const [isLoading, setIsLoading] = useState(false); const [currentPath, setCurrentPath] = useState(""); // Fetch files from backend useEffect(() => { const fetchFiles = async () => { setIsLoading(true); try { const response = await axios.get("http://localhost:3000/api/file-system/"); setFiles(response.data); } catch (error) { console.error("Failed to fetch files:", error); setFiles([]); } setIsLoading(false); }; fetchFiles(); }, []); // Create folder handler const handleCreateFolder = async (name, parentFolder) => { setIsLoading(true); try { const response = await axios.post("http://localhost:3000/api/file-system/folder", { name, parentId: parentFolder?._id || "" }); setFiles(prev => [...prev, response.data]); } catch (error) { console.error("Failed to create folder:", error); } setIsLoading(false); }; // File upload handlers const handleFileUploading = (file, parentFolder) => { return { parentId: parentFolder?._id || "" }; }; const handleFileUploaded = (response) => { const uploadedFile = JSON.parse(response); setFiles(prev => [...prev, uploadedFile]); }; // Rename handler const handleRename = async (file, newName) => { setIsLoading(true); try { await axios.patch("http://localhost:3000/api/file-system/rename", { id: file._id, newName }); // Refresh files const response = await axios.get("http://localhost:3000/api/file-system/"); setFiles(response.data); } catch (error) { console.error("Failed to rename:", error); } setIsLoading(false); }; // Delete handler const handleDelete = async (filesToDelete) => { setIsLoading(true); try { const ids = filesToDelete.map(f => f._id); await axios.delete("http://localhost:3000/api/file-system/", { data: { ids } }); // Refresh files const response = await axios.get("http://localhost:3000/api/file-system/"); setFiles(response.data); } catch (error) { console.error("Failed to delete:", error); } setIsLoading(false); }; // Copy/Move handler const handlePaste = async (items, destinationFolder, operationType) => { setIsLoading(true); try { const sourceIds = items.map(item => item._id); const endpoint = operationType === "copy" ? "/copy" : "/move"; await axios({ method: operationType === "copy" ? "POST" : "PUT", url: `http://localhost:3000/api/file-system${endpoint}`, data: { sourceIds, destinationId: destinationFolder?._id || "" } }); // Refresh files const response = await axios.get("http://localhost:3000/api/file-system/"); setFiles(response.data); } catch (error) { console.error("Failed to paste:", error); } setIsLoading(false); }; // Download handler const handleDownload = async (filesToDownload) => { try { const ids = filesToDownload.map(f => f._id); const params = ids.length === 1 ? `?files=${ids[0]}` : `?${ids.map(id => `files[]=${id}`).join('&')}`; window.location.href = `http://localhost:3000/api/file-system/download${params}`; } catch (error) { console.error("Failed to download:", error); } }; const handleError = (error, file) => { console.error(`Error with file ${file?.name}:`, error.message); }; const handleSelectionChange = (selectedFiles) => { console.log("Selected files:", selectedFiles.map(f => f.name)); }; return (
); } ``` -------------------------------- ### Get All Items - API Request Source: https://context7.com/saifullah-dev/react-file-manager/llms.txt Retrieves all files and folders from the database along with their metadata. This is a GET request to the /api/file-system/ endpoint. ```bash curl -X GET http://localhost:3000/api/file-system/ \ -H "Content-Type: application/json" ``` -------------------------------- ### Setup Express.js Backend Server for File Management Source: https://context7.com/saifullah-dev/react-file-manager/llms.txt This JavaScript snippet outlines the setup for an Express.js backend server designed for file system management. It includes configurations for MongoDB connection using Mongoose, CORS for cross-origin requests, static file serving for uploads, body parsing, and defining API routes for file system operations. It also incorporates a global error handler. ```javascript // server.js const express = require("express"); const mongoose = require("mongoose"); const cors = require("cors"); const dotenv = require("dotenv"); const fileSystemRoutes = require("./app/routes/fileSystem.routes"); const errorHandler = require("./app/middlewares/errorHandler.middleware"); dotenv.config(); const app = express(); // MongoDB connection mongoose.connect(process.env.MONGO_URI || "mongodb://localhost:27017/fileManagerDB", { useNewUrlParser: true, useUnifiedTopology: true }) .then(() => console.log("MongoDB connected successfully")) .catch(err => console.error("MongoDB connection error:", err)); // CORS configuration app.use(cors({ origin: process.env.CLIENT_URI || "http://localhost:5173" })); // Static files for uploaded content app.use(express.static("public/uploads")); // Body parsing middleware app.use(express.urlencoded({ extended: true })); app.use(express.json()); // API routes app.use("/api/file-system", fileSystemRoutes); // Global error handler app.use(errorHandler); const PORT = process.env.PORT || 3000; app.listen(PORT, () => { console.log(`Server running on http://localhost:${PORT}`); }); ``` -------------------------------- ### Clone React File Manager Repository Source: https://github.com/saifullah-dev/react-file-manager/blob/main/backend/Readme.md This command clones the React File Manager project from GitHub. It's the first step to get the backend code onto your local machine. ```bash git clone https://github.com/Saifullah-dev/react-file-manager.git ``` -------------------------------- ### Basic React File Manager Usage Source: https://github.com/saifullah-dev/react-file-manager/blob/main/README.md This example demonstrates how to integrate the FileManager component into a React application. It initializes the component with a sample file structure and imports necessary CSS for styling. The `files` prop expects an array of file/folder objects. ```jsx import { useState } from "react"; import { FileManager } from "@cubone/react-file-manager"; import "@cubone/react-file-manager/dist/style.css"; function App() { const [files, setFiles] = useState([ { name: "Documents", isDirectory: true, // Folder path: "/Documents", // Located in Root directory updatedAt: "2024-09-09T10:30:00Z", // Last updated time }, { name: "Pictures", isDirectory: true, path: "/Pictures", // Located in Root directory as well updatedAt: "2024-09-09T11:00:00Z", }, { name: "Pic.png", isDirectory: false, // File path: "/Pictures/Pic.png", // Located inside the "Pictures" folder updatedAt: "2024-09-08T16:45:00Z", size: 2048, // File size in bytes (example: 2 KB) }, ]); return ( <> ); } export default App; ``` -------------------------------- ### GET /api/file-system/ Source: https://context7.com/saifullah-dev/react-file-manager/llms.txt Retrieves all files and folders from the database with their metadata including paths, sizes, and modification timestamps. ```APIDOC ## GET /api/file-system/ ### Description Retrieves all files and folders from the database with their metadata including paths, sizes, and modification timestamps. ### Method GET ### Endpoint /api/file-system/ ### Parameters #### Query Parameters None ### Request Example ```bash curl -X GET http://localhost:3000/api/file-system/ \ -H "Content-Type: application/json" ``` ### Response #### Success Response (200) - **_id** (string) - Unique identifier for the item. - **name** (string) - Name of the file or folder. - **isDirectory** (boolean) - True if the item is a directory, false otherwise. - **path** (string) - The full path of the item in the file system. - **parentId** (string | null) - The ID of the parent directory, null if at the root. - **size** (number | null) - The size of the file in bytes, null for directories. - **mimeType** (string | null) - The MIME type of the file, null for directories. - **createdAt** (string) - Timestamp when the item was created. - **updatedAt** (string) - Timestamp when the item was last updated. #### Response Example ```json [ { "_id": "60d0fe4f5311236168a109ca", "name": "Documents", "isDirectory": true, "path": "/Documents", "parentId": null, "size": null, "mimeType": null, "createdAt": "2024-09-25T12:34:29.490Z", "updatedAt": "2024-09-25T12:34:29.490Z" }, { "_id": "50e6ge6d5347836199z314xc", "name": "Requirements.pdf", "isDirectory": false, "path": "/Documents/Requirements.pdf", "parentId": "60d0fe4f5311236168a109ca", "size": 1791868, "mimeType": "application/pdf", "createdAt": "2024-09-04T11:28:13.882Z", "updatedAt": "2024-09-04T11:28:13.882Z" } ] ``` ``` -------------------------------- ### Set Initial Directory Path in React FileManager Source: https://github.com/saifullah-dev/react-file-manager/blob/main/README.md Defines the starting directory for the FileManager component. By default, it starts at the root (''). This prop allows specifying a different initial folder, such as '/Documents'. ```jsx ``` -------------------------------- ### GET /api/file-system/download Source: https://context7.com/saifullah-dev/react-file-manager/llms.txt Downloads a single file directly or multiple files/folders as a compressed ZIP archive. ```APIDOC ## GET /api/file-system/download ### Description Downloads a single file directly or multiple files/folders as a compressed ZIP archive. ### Method GET ### Endpoint `/api/file-system/download` ### Parameters #### Query Parameters - **files** (string or array of strings) - Required - The ID(s) of the file(s) or folder(s) to download. For multiple items, this should be an array. ### Request Example ```bash # Download single file curl -X GET "http://localhost:3000/api/file-system/download?files=50e6ge6d5347836199z314xc" -O -J # Download multiple files as ZIP curl -X GET "http://localhost:3000/api/file-system/download?files[]=50e6ge6d5347836199z314xc&files[]=70f1ab5c6422347279b210db" -O -J # Download folder as ZIP curl -X GET "http://localhost:3000/api/file-system/download?files=60d0fe4f5311236168a109ca" -O -J ``` ### Response #### Success Response (200) - **Content-Disposition** (header) - Indicates the filename for a single file download or the ZIP archive. #### Response Example (Binary file or ZIP archive) #### Error Response (404 Not Found) - **error** (string) - Indicates that the requested file was not found. ``` -------------------------------- ### Get All Files/Folders API Source: https://github.com/saifullah-dev/react-file-manager/blob/main/backend/Readme.md Retrieves a list of all files and folders in the specified directory. ```APIDOC ## GET / ### Description Retrieves all files and folders from the root directory or a specified path. ### Method GET ### Endpoint / ### Parameters #### Query Parameters - **currentPath** (string) - Optional - The path of the directory to list. Defaults to root. ### Request Example `/` ### Response #### Success Response (200) - **items** (array of objects) - A list of files and folders. - **name** (string) - The name of the item. - **path** (string) - The full path to the item. - **type** (string) - 'file' or 'folder' - **size** (number) - The size of the item in bytes (for files). - **lastModified** (string) - The last modified date of the item. #### Response Example ```json { "items": [ { "name": "document.txt", "path": "/document.txt", "type": "file", "size": 1024, "lastModified": "2023-10-27T10:00:00Z" }, { "name": "images", "path": "/images", "type": "folder" } ] } ``` ``` -------------------------------- ### Custom File Preview with React Source: https://github.com/saifullah-dev/react-file-manager/blob/main/frontend/README.md Provides a callback function to render a custom preview for files. It accepts a File object and must return a React node. This allows overriding the default preview mechanism for specific file types or custom display logic. Example usage demonstrates integrating this prop for advanced preview capabilities. ```javascript filePreviewComponent: (file) => { // Custom rendering logic here return {file.name}; } ``` -------------------------------- ### Clone React File Manager Repository Source: https://github.com/saifullah-dev/react-file-manager/blob/main/README.md Instructions for cloning the React File Manager project from GitHub. This is the first step for developers who wish to contribute or set up a local development environment. ```bash git clone https://github.com/Saifullah-dev/react-file-manager.git cd react-file-manager ``` -------------------------------- ### Generate Swagger API Documentation Source: https://github.com/saifullah-dev/react-file-manager/blob/main/backend/Readme.md This command generates the Swagger API documentation for the file management backend. The generated documentation can be accessed at http://localhost:3000/api-docs/. ```bash npm run genDocs ``` -------------------------------- ### Create Folder API Source: https://github.com/saifullah-dev/react-file-manager/blob/main/backend/Readme.md This endpoint allows you to create a new folder within the file system. ```APIDOC ## POST /folder ### Description Creates a new folder at the specified location. ### Method POST ### Endpoint /folder ### Parameters #### Request Body - **folderName** (string) - Required - The name of the folder to create. - **currentPath** (string) - Optional - The path where the folder should be created. Defaults to root. ### Request Example ```json { "folderName": "new_folder", "currentPath": "/existing_folder" } ``` ### Response #### Success Response (201) - **message** (string) - Confirmation message that the folder was created. - **folder** (object) - Details of the created folder. - **name** (string) - The name of the created folder. - **path** (string) - The full path to the created folder. - **type** (string) - 'folder' #### Response Example ```json { "message": "Folder created successfully.", "folder": { "name": "new_folder", "path": "/existing_folder/new_folder", "type": "folder" } } ``` ``` -------------------------------- ### POST /api/file-system/folder Source: https://context7.com/saifullah-dev/react-file-manager/llms.txt Creates a new folder in the specified parent directory or at the root level, creating the physical directory on the filesystem and storing metadata in the database. ```APIDOC ## POST /api/file-system/folder ### Description Creates a new folder in the specified parent directory or at the root level, creating the physical directory on the filesystem and storing metadata in the database. ### Method POST ### Endpoint /api/file-system/folder ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **name** (string) - Required - The name of the new folder. - **parentId** (string) - Optional - The ID of the parent directory. If empty or null, the folder is created at the root. ### Request Example ```json { "name": "Pictures", "parentId": "" } ``` ### Response #### Success Response (201 Created) - **_id** (string) - Unique identifier for the created folder. - **name** (string) - Name of the folder. - **isDirectory** (boolean) - Always true for a folder. - **path** (string) - The full path of the created folder. - **parentId** (string | null) - The ID of the parent directory. - **createdAt** (string) - Timestamp when the folder was created. - **updatedAt** (string) - Timestamp when the folder was last updated. #### Response Example ```json { "_id": "60d0fe4f5311236168a109cb", "name": "Pictures", "isDirectory": true, "path": "/Pictures", "parentId": null, "createdAt": "2024-09-25T12:34:29.490Z", "updatedAt": "2024-09-25T12:34:29.490Z" } ``` #### Error Response (400 Bad Request) - **error** (string) - Description of the error, e.g., "Folder already exists!" #### Error Response Example ```json { "error": "Folder already exists!" } ``` ``` -------------------------------- ### Handle File/Folder Download in React Source: https://github.com/saifullah-dev/react-file-manager/blob/main/README.md The `onDownload` callback is executed when one or more files or folders are initiated for download. It receives an array containing the files/folders to be downloaded. This is where you would typically trigger the download process, possibly by generating download links or initiating server-side processing. ```javascript const handleDownload = (filesToDownload) => { console.log('Downloading files:', filesToDownload); // Initiate download process }; ``` -------------------------------- ### Download File(s)/Folder(s) API Source: https://github.com/saifullah-dev/react-file-manager/blob/main/backend/Readme.md Initiates the download of specified files or folders. ```APIDOC ## GET /download ### Description Allows downloading of individual files or a ZIP archive of multiple files/folders. ### Method GET ### Endpoint /download ### Parameters #### Query Parameters - **paths** (string) - Required - Comma-separated list of paths to the files/folders to download. ### Request Example `/download?paths=/path/to/file1.txt,/path/to/folderA` ### Response #### Success Response (200) - The response will be a file download stream. If multiple items are selected, it will be a ZIP archive. ``` -------------------------------- ### Handle New Folder Creation in React Source: https://github.com/saifullah-dev/react-file-manager/blob/main/README.md The `onCreateFolder` callback is invoked when a new folder is created. It receives the folder name and its parent folder as arguments. Implement this to update your application's file state by making an API call to your server to create the folder. ```javascript const handleCreateFolder = (name, parentFolder) => { // API call to create folder on server console.log(`Creating folder: ${name} in ${parentFolder.path}`); // Update state with new folder }; ``` -------------------------------- ### Create Folder - API Request Source: https://context7.com/saifullah-dev/react-file-manager/llms.txt Creates a new folder. Supports creating folders at the root or within a specified parent directory. Requires 'name' and 'parentId' in the request body. Returns a 201 Created status on success or 400 Bad Request if the folder already exists. ```bash # Create a folder in root directory curl -X POST http://localhost:3000/api/file-system/folder \ -H "Content-Type: application/json" \ -d '{ "name": "Pictures", "parentId": "" }' # Create a folder inside another folder curl -X POST http://localhost:3000/api/file-system/folder \ -H "Content-Type: application/json" \ -d '{ "name": "Vacation Photos", "parentId": "60d0fe4f5311236168a109ca" }' ``` -------------------------------- ### POST /api/file-system/copy Source: https://context7.com/saifullah-dev/react-file-manager/llms.txt Copies one or multiple files or folders to a destination directory. It recursively copies all contents and creates new database entries. ```APIDOC ## POST /api/file-system/copy ### Description Copies one or multiple files or folders to a destination directory, recursively copying all contents and creating new database entries. ### Method POST ### Endpoint `/api/file-system/copy` ### Parameters #### Request Body - **sourceIds** (array of strings) - Required - An array of IDs of the items to copy. - **destinationId** (string) - Required - The ID of the destination directory. An empty string or null can be used to copy to the root directory. ### Request Example ```json { "sourceIds": ["50e6ge6d5347836199z314xc"], "destinationId": "60d0fe4f5311236168a109cb" } ``` ### Response #### Success Response (200) - **message** (string) - Indicates successful copy operation. #### Response Example ```json { "message": "Item(s) copied successfully!" } ``` #### Error Response (400 Bad Request) - **error** (string) - Indicates an invalid destination ID. #### Error Response (404 Not Found) - **error** (string) - Indicates that one or more of the provided source IDs do not exist. ``` -------------------------------- ### Handle File/Folder Opening in React Source: https://github.com/saifullah-dev/react-file-manager/blob/main/README.md The `onFileOpen` callback is triggered when a user attempts to open a file or folder. It receives the `file` object that was opened. Implement this callback to define the behavior when a file is opened, such as displaying file content or navigating into a folder. ```javascript const handleFileOpen = (file) => { console.log('Opening file:', file.name); // Logic to open file or navigate folder }; ``` -------------------------------- ### File Upload Configuration Object Source: https://github.com/saifullah-dev/react-file-manager/blob/main/frontend/README.md Defines settings for uploading files, including the target URL, HTTP method (POST or PUT), and optional headers. This object allows specifying how and where files are uploaded, with support for custom authentication tokens or headers required by the server. The default method is POST. ```javascript fileUploadConfig: { url: "https://example.com/upload", method: "PUT", headers: { "Authorization": "Bearer YOUR_TOKEN", "X-Custom-Header": "some-value" } } ``` -------------------------------- ### Upload File API Source: https://github.com/saifullah-dev/react-file-manager/blob/main/backend/Readme.md This endpoint handles the upload of files to the file system. ```APIDOC ## POST /upload ### Description Uploads a file to the specified directory. ### Method POST ### Endpoint /upload ### Parameters #### Query Parameters - **currentPath** (string) - Optional - The path where the file should be uploaded. Defaults to root. #### Request Body - **file** (file) - Required - The file to upload. ### Request Example (Refer to multipart/form-data for file uploads) ### Response #### Success Response (200) - **message** (string) - Confirmation message that the file was uploaded. - **file** (object) - Details of the uploaded file. - **name** (string) - The name of the uploaded file. - **path** (string) - The full path to the uploaded file. - **type** (string) - 'file' #### Response Example ```json { "message": "File uploaded successfully.", "file": { "name": "my_document.pdf", "path": "/uploads/my_document.pdf", "type": "file" } } ``` ``` -------------------------------- ### Custom File Preview with React Source: https://github.com/saifullah-dev/react-file-manager/blob/main/README.md A callback function prop that allows for custom rendering of file previews. It receives a file object and must return a React.ReactNode. This enables sophisticated, application-specific preview components beyond the default behavior. ```typescript (file: [File](#-file-structure)) => React.ReactNode ``` -------------------------------- ### Configure React File Manager Component Source: https://context7.com/saifullah-dev/react-file-manager/llms.txt This snippet shows how to configure the FileManager component with various props such as primary color, font family, file handling options (max file size, accepted types, preview), navigation settings, and permissions. It sets up the basic structure and functionality for the file manager UI. ```jsx width="100%" primaryColor="#6155b4" fontFamily="'Nunito Sans', sans-serif" // File handling maxFileSize={10485760} // 10MB in bytes acceptedFileTypes=".pdf,.doc,.docx,.txt,.png,.jpg,.jpeg" enableFilePreview={true} filePreviewPath="http://localhost:3000" // Navigation options collapsibleNav={true} defaultNavExpanded={true} // Permissions permissions={{ create: true, upload: true, move: true, copy: true, rename: true, download: true, delete: true }} // Language language="en-US" /> ); } export default App; ``` ``` -------------------------------- ### POST /api/file-system/upload Source: https://context7.com/saifullah-dev/react-file-manager/llms.txt Uploads a file using multipart/form-data with optional parent folder specification, storing the file physically and recording metadata. ```APIDOC ## POST /api/file-system/upload ### Description Uploads a file using multipart/form-data with optional parent folder specification, storing the file physically and recording metadata. ### Method POST ### Endpoint /api/file-system/upload ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **file** (file) - Required - The file to upload. - **parentId** (string) - Optional - The ID of the parent directory. If empty or null, the file is uploaded to the root. ### Request Example ```bash # Upload file to root directory curl -X POST http://localhost:3000/api/file-system/upload \ -F "file=@/path/to/local/document.pdf" \ -F "parentId=" ``` ### Response #### Success Response (201 Created) - **_id** (string) - Unique identifier for the uploaded file. - **name** (string) - Name of the file. - **isDirectory** (boolean) - Always false for a file. - **path** (string) - The full path of the uploaded file. - **parentId** (string | null) - The ID of the parent directory. - **size** (number) - The size of the file in bytes. - **mimeType** (string) - The MIME type of the file. - **createdAt** (string) - Timestamp when the file was uploaded. - **updatedAt** (string) - Timestamp when the file was last updated. #### Response Example ```json { "_id": "50e6ge6d5347836199z314xc", "name": "document.pdf", "isDirectory": false, "path": "/Documents/document.pdf", "parentId": "60d0fe4f5311236168a109ca", "size": 2048576, "mimeType": "application/pdf", "createdAt": "2024-09-04T11:28:13.882Z", "updatedAt": "2024-09-04T11:28:13.882Z" } ``` #### Error Response (400 Bad Request) - **error** (string) - Description of the error, e.g., "Invalid parentId!" #### Error Response Example ```json { "error": "Invalid parentId!" } ``` ``` -------------------------------- ### Multi-language Support in React File Manager Source: https://context7.com/saifullah-dev/react-file-manager/llms.txt Enables multi-language support for the React File Manager component using the `language` prop. A dropdown allows users to select their preferred language from a predefined list of supported languages. The component dynamically updates its UI based on the selected language. ```jsx import { FileManager } from "@cubone/react-file-manager"; import { useState } from "react"; function App() { const [language, setLanguage] = useState("en-US"); const availableLanguages = [ { code: "en-US", name: "English", flag: "🇺🇸" }, { code: "es-ES", name: "Español", flag: "🇪🇸" }, { code: "fr-FR", name: "Français", flag: "🇫🇷" }, { code: "de-DE", name: "Deutsch", flag: "🇩🇪" }, { code: "ja-JP", name: "日本語", flag: "🇯🇵" }, { code: "zh-CN", name: "中文", flag: "🇨🇳" }, { code: "ar-SA", name: "العربية", flag: "🇸🇦" }, { code: "ru-RU", name: "Русский", flag: "🇷🇺" }, { code: "pt-BR", name: "Português", flag: "🇧🇷" }, { code: "hi-IN", name: "हिन्दी", flag: "🇮🇳" }, { code: "tr-TR", name: "Türkçe", flag: "🇹🇷" }, { code: "ko-KR", name: "한국어", flag: "🇰🇷" } ]; return (
{/* Language selector */}
); } ``` -------------------------------- ### Copy Item API Source: https://github.com/saifullah-dev/react-file-manager/blob/main/backend/Readme.md This endpoint allows copying files or folders. ```APIDOC ## POST /copy ### Description Copies one or more files or folders to a new location. ### Method POST ### Endpoint /copy ### Parameters #### Request Body - **sourcePaths** (array of strings) - Required - An array of paths to the items to be copied. - **destinationPath** (string) - Required - The path where the items should be copied to. ### Request Example ```json { "sourcePaths": ["/path/to/file1.txt", "/path/to/folderA"], "destinationPath": "/path/to/new_location" } ``` ### Response #### Success Response (200) - **message** (string) - Confirmation message indicating the items were copied. #### Response Example ```json { "message": "Items copied successfully." } ``` ``` -------------------------------- ### Copy Items API Request (Bash) Source: https://context7.com/saifullah-dev/react-file-manager/llms.txt Copies one or multiple files or folders to a specified destination directory. This operation recursively copies all contents and creates new database entries. It requires source IDs and a destination ID. ```bash curl -X POST http://localhost:3000/api/file-system/copy \ -H "Content-Type: application/json" \ -d '{ \ "sourceIds": ["50e6ge6d5347836199z314xc"], \ "destinationId": "60d0fe4f5311236168a109cb" \ }' ``` ```bash curl -X POST http://localhost:3000/api/file-system/copy \ -H "Content-Type: application/json" \ -d '{ \ "sourceIds": [ \ "50e6ge6d5347836199z314xc", \ "60d0fe4f5311236168a109ca" \ ], \ "destinationId": "" \ }' ``` -------------------------------- ### Download Files API Request (Bash) Source: https://context7.com/saifullah-dev/react-file-manager/llms.txt Downloads a single file directly or multiple files/folders as a compressed ZIP archive. It accepts file IDs as query parameters. The `-O` flag saves the output to a file, and `-J` suggests a filename. ```bash curl -X GET "http://localhost:3000/api/file-system/download?files=50e6ge6d5347836199z314xc" \ -O -J ``` ```bash curl -X GET "http://localhost:3000/api/file-system/download?files[]=50e6ge6d5347836199z314xc&files[]=70f1ab5c6422347279b210db" \ -O -J ``` ```bash curl -X GET "http://localhost:3000/api/file-system/download?files=60d0fe4f5311236168a109ca" \ -O -J ``` -------------------------------- ### Database Schema for File System Metadata (MongoDB/Mongoose) Source: https://context7.com/saifullah-dev/react-file-manager/llms.txt Defines the MongoDB schema for storing file and folder metadata using Mongoose. It includes fields for name, type, path, parent ID, size, MIME type, and timestamps. Indexes are set up for efficient querying by parent ID and path. ```javascript const mongoose = require("mongoose"); const fileSystemSchema = new mongoose.Schema( { name: { type: String, required: true }, isDirectory: { type: Boolean, required: true }, path: { type: String, required: true, unique: true }, parentId: { type: mongoose.Schema.Types.ObjectId, ref: "FileSystem", default: null // null for root-level items }, size: { type: Number, default: null // Only for files }, mimeType: { type: String, default: null // Only for files } }, { timestamps: true // Adds createdAt and updatedAt } ); // Index for faster queries fileSystemSchema.index({ parentId: 1 }); fileSystemSchema.index({ path: 1 }); const FileSystem = mongoose.model("FileSystem", fileSystemSchema); module.exports = FileSystem; ``` -------------------------------- ### File Upload Configuration Object Source: https://github.com/saifullah-dev/react-file-manager/blob/main/README.md Defines the configuration for uploading files. It specifies the URL for the upload endpoint, an optional HTTP method (POST or PUT), and optional headers for authentication or custom data. This object is crucial for integrating file uploads with a backend service. ```typescript { url: string; method?: "POST" | "PUT"; headers?: { [key: string]: string }; } ``` -------------------------------- ### PUT /api/file-system/move Source: https://context7.com/saifullah-dev/react-file-manager/llms.txt Moves one or multiple files or folders to a destination directory, updating filesystem and database records recursively for all children. ```APIDOC ## PUT /api/file-system/move ### Description Moves one or multiple files or folders to a destination directory, updating filesystem and database records recursively for all children. ### Method PUT ### Endpoint `/api/file-system/move` ### Parameters #### Request Body - **sourceIds** (array of strings) - Required - An array of IDs of the items to move. - **destinationId** (string or null) - Required - The ID of the destination directory. `null` can be used to move to the root directory. ### Request Example ```json { "sourceIds": ["50e6ge6d5347836199z314xc"], "destinationId": "60d0fe4f5311236168a109cb" } ``` ### Response #### Success Response (200) - **message** (string) - Indicates successful move operation. #### Response Example ```json { "message": "Item(s) moved successfully!" } ``` #### Error Response (400 Bad Request) - **error** (string) - Indicates that one or more of the provided source IDs are invalid. ``` -------------------------------- ### Move Item API Source: https://github.com/saifullah-dev/react-file-manager/blob/main/backend/Readme.md Moves files or folders from one location to another. ```APIDOC ## POST /move ### Description Moves one or more files or folders to a new location. ### Method POST ### Endpoint /move ### Parameters #### Request Body - **sourcePaths** (array of strings) - Required - An array of paths to the items to be moved. - **destinationPath** (string) - Required - The path where the items should be moved to. ### Request Example ```json { "sourcePaths": ["/path/to/file1.txt", "/path/to/folderA"], "destinationPath": "/path/to/new_location" } ``` ### Response #### Success Response (200) - **message** (string) - Confirmation message indicating the items were moved. #### Response Example ```json { "message": "Items moved successfully." } ``` ``` -------------------------------- ### Implement Custom File Preview Component in React Source: https://context7.com/saifullah-dev/react-file-manager/llms.txt This code demonstrates how to create and use custom preview components for different file types (images, PDFs, and others) within the FileManager component. It utilizes conditional rendering based on mimeType to display appropriate previews, enhancing user experience by providing type-specific viewers. ```jsx import { FileManager } from "@cubone/react-file-manager"; import "@cubone/react-file-manager/dist/style.css"; function App() { // Custom preview component for images const CustomImagePreviewer = ({ file }) => { return (
{file.name}

{file.name}

Size: {(file.size / 1024).toFixed(2)} KB

Modified: {new Date(file.updatedAt).toLocaleDateString()}

); }; // Custom preview for PDFs using iframe const CustomPDFPreviewer = ({ file }) => { return (