Skip to content

Instantly share code, notes, and snippets.

@hungdev
Last active November 2, 2024 07:10
Show Gist options
  • Save hungdev/b3fc83762716bf60aecc7b71f979c7b7 to your computer and use it in GitHub Desktop.
Save hungdev/b3fc83762716bf60aecc7b71f979c7b7 to your computer and use it in GitHub Desktop.
filebrowser rest api for nodejs

Many programming projects need a quick and simple place to store some files which is currently way more difficult (and/or expensive) than it should be. FileBrowser has a lot of potential to be automated in the sense that it does one thing and does one thing well: Storing and retrieving files.

However, the documentation of the API is beyond lacking (i.e. it does not exist). Assuming people will only use the web interface is ignoring a massive possible userbase for this application. As a start, I have created a short example in nodejs on how to use the REST API to obtain a JWT token, and subsequently use it to upload a file, and then download a file. Please PLEASE just add ANY api documentation, this took me several hours...

I start the service using docker-compose (make sure you create the DATA_DIR beforehand):

version: '3'
services:
  filebrowser:
    image: filebrowser/filebrowser
    ports:
      - 8080:80
    volumes:
      - /home/<username>/FileBrowser/DATA_DIR:/srv

Then I start it using docker-compose up -d, and use the following node script to interact with the system

import axios from 'axios';
import fs from 'fs';

// Function to get the access token from the FileBrowser server
async function getToken() {
	console.log('Requesting access token...');

	try {
		const response = await axios.post('http://localhost:8080/api/login', {
			username: 'admin', // CHANGE THIS IN THE FRONTEND
			password: 'admin' // CHANGE THIS IN THE FRONTEND
		});
		console.log('Access token received.');
		return response.data;
	} catch (error) {
		console.error('Error while requesting access token:', error);
	}
}

// Function to upload a text file to the FileBrowser server
async function uploadFile(token) {
	console.log('Uploading file...');

	// Read the file into a string
	const fileContents = fs.readFileSync('SomeDocumentToUpload.txt', 'utf8');

	try {
		// Send a POST request to the FileBrowser server
		const res = await axios.post(
			'http://localhost:8080/api/resources/document.txt?override=true',
			fileContents,
			{
				headers: {
					'Content-Type': 'text/plain', // ADJUST THIS PER FILETYPE (img, pdf, etc)
					'X-Auth': `${token}` // WHY NOT USE AUTH HEADER?!
				}
			}
		);

		console.log('File uploaded successfully:', res.data);
	} catch (error) {
		console.error('Error while uploading file:', error);
	}
}

// Function to download a text file from the FileBrowser server
async function downloadFile(token) {
	console.log('Downloading file...');

	const url = 'http://localhost:8080/api/raw/document.txt'; // WHY USE DIFFERENT ENDPOINTS TO UPLOAD AND DOWNLOAD? (resources vs raw)

	try {
		const response = await axios({
			method: 'GET',
			url: url,
			responseType: 'stream',
			headers: {
				'X-Auth': `${token}`
			}
		});

		const writer = fs.createWriteStream('DownloadedTextFile.txt');

		response.data.pipe(writer);

		return new Promise((resolve, reject) ={
			writer.on('finish', () ={
				console.log('File downloaded successfully.');
				resolve();
			});
			writer.on('error', (error) ={
				console.error('Error while downloading file:', error);
				reject(error);
			});
		});
	} catch (error) {
		console.error('Error while requesting file download:', error);
	}
}

// Main function to control the flow of the program
async function main() {
	const token = await getToken();

	if (token) {
		await uploadFile(token);
		await downloadFile(token);
	} else {
		console.log('No access token received. Aborting.');
	}
}

// Catch any unhandled Promise rejections
process.on('unhandledRejection', (reason, promise) ={
	console.error('Unhandled Rejection at:', promise, 'reason:', reason);
});

// Start the program
main();

the endpoint to get all the files:

const axios = require('axios');

let config = {
  method: 'get',
  url: 'https://your_host/api/resources',
  headers: { 
    'X-Auth': 'your_token'
  }
};

axios.request(config)
.then((response) ={
  console.log(JSON.str

I hope people in the future find this and it saves them time. I got stuck on 401 authorization error for a seriously long time before I figured out I need an X-Auth instead of the standard Authorization: Bearer <token>...

filebrowser/filebrowser#2551

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment