Get started in three steps
Upload your first file to Filejar in under 5 minutes.
Step 1: Install and setup
Install the Filejar client:
Get your API key from the Filejar dashboard and set it as an environment variable:
export FILEJAR_API_KEY="your-api-key-here"
Step 2: Upload your first file
Create a simple script to upload a file:
import Filejar from 'filejar';
import { readFile } from 'fs/promises';
// Initialize Filejar client
const filejar = new Filejar({
apiKey: process.env.FILEJAR_API_KEY,
});
// Read a file from your filesystem
const fileBuffer = await readFile('./example.pdf');
const file = new File([fileBuffer], 'example.pdf', {
type: 'application/pdf',
});
// Upload to Filejar
const result = await filejar.upload.uploadFile([file]);
// Get the uploaded file details
const uploadResult = result.response[0];
const acknowledged = result.acknowledge[0];
// Your file is now available at:
const fileUrl = `https://cdn.filejar.dev/${uploadResult.key}`;
console.log('File uploaded successfully!');
console.log('File URL:', fileUrl);
console.log('File size:', acknowledged.size, 'bytes');
Step 3: Use your file
Your uploaded file is immediately available via CDN. Use the URL anywhere:
<!-- In HTML -->
<img src="https://cdn.filejar.dev/your-file-key" alt="Uploaded image" />
<!-- Or in your application -->
<a href="https://cdn.filejar.dev/your-file-key">Download file</a>
Complete example
Here’s a complete working example:
import Filejar from 'filejar';
import { readFile } from 'fs/promises';
async function uploadFile() {
try {
// Initialize client
const filejar = new Filejar({
apiKey: process.env.FILEJAR_API_KEY,
});
// Read file
const buffer = await readFile('./my-file.pdf');
const file = new File([buffer], 'my-file.pdf', {
type: 'application/pdf',
});
// Upload
const result = await filejar.upload.uploadFile([file]);
if (!result.response || result.response.length === 0) {
throw new Error('Upload failed');
}
const uploadResult = result.response[0];
const acknowledged = result.acknowledge[0];
if ('error' in acknowledged) {
throw new Error(acknowledged.error);
}
// Success!
const fileUrl = `https://cdn.filejar.dev/${uploadResult.key}`;
return {
key: uploadResult.key,
url: fileUrl,
size: acknowledged.size,
contentType: acknowledged.content_type,
};
} catch (error) {
if (error instanceof Filejar.APIError) {
console.error('API Error:', error.message);
} else {
console.error('Error:', error);
}
throw error;
}
}
// Run it
uploadFile()
.then(result => console.log('Success:', result))
.catch(error => console.error('Failed:', error));
Next steps
Now that you’ve uploaded your first file, explore more:
Pro tip: Store the file key in your database to retrieve files later. The key is all you need to construct the file URL!