Integrate tfLink's temporary file upload API into your applications for seamless, secure file sharing. This comprehensive guide covers authentication, endpoints, code examples, and best practices using tfLink's production API.
Table of Contents
API Overview
tfLink's API provides a simple, powerful interface for temporary file uploads with the following features:
- Single Endpoint: POST to
/api/upload
- File Support: All file types up to 100MB
- Global CDN: Powered by Cloudflare Workers
- Anonymous & Authenticated: Both upload modes supported
- Auto-cleanup: 7-day retention for anonymous uploads
Authentication Methods
Anonymous Uploads
No authentication required. Files are automatically deleted after 7 days.
Simple Anonymous Upload
curl -X POST \
-F "file=@document.pdf" \
https://tmpfile.link/api/upload
Authenticated Uploads
For authenticated uploads, include X-User-Id
and X-Auth-Token
headers. Files have longer retention periods.
Authenticated Upload
curl -X POST \
-H "X-User-Id: YOUR_USER_ID" \
-H "X-Auth-Token: YOUR_AUTH_TOKEN" \
-F "file=@document.pdf" \
https://tmpfile.link/api/upload
Upload Endpoint
Request Details
HTTP Request Format
POST /api/upload HTTP/1.1
Host: tmpfile.link
Content-Type: multipart/form-data
# Optional authentication headers:
X-User-Id: YOUR_USER_ID
X-Auth-Token: YOUR_AUTH_TOKEN
# Form data:
file=@your-file.ext
Response Format
Anonymous Upload Response
Anonymous Response Example
{
"fileName": "example.png",
"downloadLink": "https://d.tmpfile.link/public/2024-12-07/a1b2c3d4-e5f6-7890-abcd-ef1234567890/example.png",
"downloadLinkEncoded": "https://d.tmpfile.link/public%2F2024-12-07%2Fa1b2c3d4-e5f6-7890-abcd-ef1234567890%2Fexample.png",
"size": 102400,
"type": "image/png",
"uploadedTo": "public"
}
Authenticated Upload Response
Authenticated Response Example
{
"fileName": "document.pdf",
"downloadLink": "https://d.tmpfile.link/users/YOUR_USER_ID/2024-12-07/uuid-example/document.pdf",
"downloadLinkEncoded": "https://d.tmpfile.link/users%2FYOUR_USER_ID%2F2024-12-07%2Fuuid-example%2Fdocument.pdf",
"size": 2048000,
"type": "application/pdf",
"uploadedTo": "user: YOUR_USER_ID"
}
Code Examples
JavaScript/Node.js Integration
Browser Upload with Fetch API
async function uploadToTfLink(file, userCredentials = null) {
const formData = new FormData();
formData.append('file', file);
const headers = {};
if (userCredentials) {
headers['X-User-Id'] = userCredentials.userId;
headers['X-Auth-Token'] = userCredentials.authToken;
}
try {
const response = await fetch('https://tmpfile.link/api/upload', {
method: 'POST',
headers: headers,
body: formData
});
if (!response.ok) {
throw new Error(`Upload failed: ${response.status}`);
}
const result = await response.json();
return {
success: true,
data: result
};
} catch (error) {
return {
success: false,
error: error.message
};
}
}
// Usage examples:
// Anonymous upload
const result1 = await uploadToTfLink(fileObject);
// Authenticated upload
const result2 = await uploadToTfLink(fileObject, {
userId: 'your-user-id',
authToken: 'your-auth-token'
});
Python Integration
Python Upload Function
import requests
import os
def upload_to_tflink(file_path, user_id=None, auth_token=None):
"""Upload file to tfLink and return download link"""
url = "https://tmpfile.link/api/upload"
headers = {}
# Add authentication headers if provided
if user_id and auth_token:
headers['X-User-Id'] = user_id
headers['X-Auth-Token'] = auth_token
# Prepare file for upload
with open(file_path, 'rb') as file:
files = {"file": (os.path.basename(file_path), file)}
try:
response = requests.post(url, headers=headers, files=files)
response.raise_for_status()
result = response.json()
return {
'success': True,
'file_name': result['fileName'],
'download_link': result['downloadLink'],
'size': result['size'],
'type': result['type'],
'uploaded_to': result['uploadedTo']
}
except requests.exceptions.RequestException as e:
return {
'success': False,
'error': str(e)
}
# Usage examples:
# Anonymous upload
result = upload_to_tflink("document.pdf")
if result['success']:
print(f"File uploaded: {result['download_link']}")
else:
print(f"Upload failed: {result['error']}")
# Authenticated upload
result = upload_to_tflink(
"document.pdf",
user_id="your-user-id",
auth_token="your-auth-token"
)
PHP Integration
PHP Upload Function
$file];
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $postData);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
// Add authentication headers if provided
if ($userId && $authToken) {
curl_setopt($ch, CURLOPT_HTTPHEADER, [
"X-User-Id: $userId",
"X-Auth-Token: $authToken"
]);
}
$response = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
if ($httpCode === 200) {
return json_decode($response, true);
} else {
return [
'success' => false,
'error' => "HTTP $httpCode: $response"
];
}
}
// Usage examples:
$result = uploadToTfLink('document.pdf');
if (isset($result['downloadLink'])) {
echo "File uploaded: " . $result['downloadLink'];
} else {
echo "Upload failed: " . $result['error'];
}
?>
PowerShell Integration
Windows PowerShell Upload
# Anonymous upload function
function Upload-ToTfLink {
param(
[string]$FilePath,
[string]$UserId = $null,
[string]$AuthToken = $null
)
$uri = "https://tmpfile.link/api/upload"
$headers = @{}
# Add authentication if provided
if ($UserId -and $AuthToken) {
$headers["X-User-Id"] = $UserId
$headers["X-Auth-Token"] = $AuthToken
}
try {
if ($headers.Count -gt 0) {
$response = Invoke-RestMethod -Uri $uri -Method Post -InFile $FilePath -ContentType "multipart/form-data" -Headers $headers
} else {
$response = Invoke-RestMethod -Uri $uri -Method Post -InFile $FilePath -ContentType "multipart/form-data"
}
return $response
} catch {
Write-Error "Upload failed: $($_.Exception.Message)"
return $null
}
}
# Usage examples:
$result = Upload-ToTfLink -FilePath "C:\path\to\document.pdf"
if ($result) {
Write-Host "File uploaded: $($result.downloadLink)"
}
# Authenticated upload
$result = Upload-ToTfLink -FilePath "C:\path\to\document.pdf" -UserId "your-user-id" -AuthToken "your-auth-token"
Error Handling
tfLink API returns standard HTTP status codes. Handle these common scenarios:
Common Error Responses
// File too large (>100MB)
HTTP 413: Payload Too Large
{
"error": "File size exceeds 100MB limit"
}
// Invalid file or request
HTTP 400: Bad Request
{
"error": "No file provided or invalid request"
}
// Authentication issues
HTTP 401: Unauthorized
{
"error": "Invalid authentication credentials"
}
// Server error
HTTP 500: Internal Server Error
{
"error": "Server processing error"
}
Robust Error Handling Example
JavaScript Error Handling
async function uploadWithRetry(file, credentials = null, maxRetries = 3) {
for (let attempt = 1; attempt <= maxRetries; attempt++) {
try {
const result = await uploadToTfLink(file, credentials);
if (result.success) {
return result;
}
// Handle specific error cases
if (result.error.includes('413')) {
throw new Error('File too large (max 100MB)');
}
if (result.error.includes('401')) {
throw new Error('Authentication failed - check credentials');
}
// Retry for temporary errors
if (attempt < maxRetries && result.error.includes('500')) {
console.log(`Upload attempt ${attempt} failed, retrying...`);
await new Promise(resolve => setTimeout(resolve, 1000 * attempt));
continue;
}
throw new Error(result.error);
} catch (error) {
if (attempt === maxRetries) {
throw error;
}
console.log(`Attempt ${attempt} failed: ${error.message}`);
await new Promise(resolve => setTimeout(resolve, 1000 * attempt));
}
}
}
Best Practices
File Validation
- Size Check: Validate files are under 100MB before upload
- Type Validation: Check file types if your application has restrictions
- Name Sanitization: Ensure file names are safe and valid
Performance Optimization
- Progress Tracking: Show upload progress for better UX
- Chunked Uploads: For large files, consider chunking (not currently supported by tfLink)
- Parallel Processing: Upload multiple files concurrently
- Compression: Compress files when appropriate before upload
Security Considerations
- Authentication: Store credentials securely, never in client-side code
- HTTPS Only: Always use encrypted connections
- Input Validation: Validate all user inputs before processing
- Error Messages: Don't expose sensitive information in error responses
Integration Tips
File Upload Progress Example
function uploadWithProgress(file, credentials = null, onProgress) {
return new Promise((resolve, reject) => {
const xhr = new XMLHttpRequest();
const formData = new FormData();
formData.append('file', file);
// Track upload progress
xhr.upload.addEventListener('progress', (e) => {
if (e.lengthComputable) {
const percentComplete = (e.loaded / e.total) * 100;
onProgress(percentComplete);
}
});
xhr.addEventListener('load', () => {
if (xhr.status === 200) {
resolve(JSON.parse(xhr.responseText));
} else {
reject(new Error(`Upload failed: ${xhr.status}`));
}
});
xhr.addEventListener('error', () => {
reject(new Error('Network error occurred'));
});
// Add authentication headers if provided
if (credentials) {
xhr.setRequestHeader('X-User-Id', credentials.userId);
xhr.setRequestHeader('X-Auth-Token', credentials.authToken);
}
xhr.open('POST', 'https://tmpfile.link/api/upload');
xhr.send(formData);
});
}
// Usage with progress callback
uploadWithProgress(file, null, (progress) => {
console.log(`Upload progress: ${progress.toFixed(1)}%`);
}).then(result => {
console.log('Upload complete:', result.downloadLink);
}).catch(error => {
console.error('Upload failed:', error);
});
Start Using tfLink API Today
Experience fast, reliable temporary file uploads with tfLink's API. Built on Cloudflare Workers with global CDN delivery and automatic cleanup.
Try tfLink API →