To build a Node.js application to upload files to Cloudflare R2 and provide the user with a downloadable URL, both a frontend and backend are necessary. Here's a description of how to structure the application without requesting any credentials or using copy-pasted code. Please note that you need to set up Cloudflare R2 and have your API keys ready to interact with their service.
Frontend (HTML file):
<!-- ./public/index.html -->
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>File Uploader</title>
</head>
<body>
<h1>Upload your file</h1>
<form id="uploadForm" enctype="multipart/form-data">
<input type="file" name="file" required>
<button type="submit">Upload File</button>
</form>
<div id="uploadResult"></div>
<script>
document.getElementById('uploadForm').addEventListener('submit', async function(e) {
e.preventDefault();
const formData = new FormData(this);
const response = await fetch('/upload', {
method: 'POST',
body: formData
});
const result = await response.json();
document.getElementById('uploadResult').textContent =
response.status === 200 ? `File URL: ${result.url}` : `Error: ${result.message}`;
});
</script>
</body>
</html>
Backend (Node.js):
// ./server.js
const express = require('express');
const multer = require('multer');
const fetch = require('node-fetch');
const FormData = require('form-data');
// Place your Cloudflare R2 credentials here
const CLOUDFLARE_ACCOUNT_ID = 'your-cloudflare-account-id';
const CLOUDFLARE_AUTH_EMAIL = 'your-cloudflare-auth-email';
const CLOUDFLARE_AUTH_KEY = 'your-cloudflare-auth-key';
const CLOUDFLARE_BUCKET_NAME = 'your-bucket-name';
const app = express();
const upload = multer(); // In-memory storage
// Serve static files from public folder
app.use(express.static('public'));
// Endpoint to handle file uploads
app.post('/upload', upload.single('file'), async (req, res) => {
try {
if (!req.file) {
throw new Error('No file uploaded.');
}
const fileStream = req.file.buffer;
// Prepare upload request to Cloudflare R2
const formData = new FormData();
formData.append('file', fileStream, req.file.originalname);
// POST request to Cloudflare R2
const r2Response = await fetch(`https://${CLOUDFLARE_ACCOUNT_ID}.r2.cloudflarestorage.com/${CLOUDFLARE_BUCKET_NAME}/${req.file.originalname}`, {
method: 'PUT',
headers: {
'X-Auth-Email': CLOUDFLARE_AUTH_EMAIL,
'X-Auth-Key': CLOUDFLARE_AUTH_KEY
},
body: fileStream
});
if (!r2Response.ok) {
throw new Error(`Failed to upload file: ${r2Response.statusText}`);
}
const fileUrl = `https://${CLOUDFLARE_BUCKET_NAME}.r2.cf/${req.file.originalname}`;
res.json({ url: fileUrl });
} catch (err) {
res.status(500).json({ message: err.message });
}
});
const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
console.log(`Server is running on port ${PORT}`);
});
Installation & Running the Server
- Create a new folder for your project.
- Inside the project folder, create two directories:
public (for storing frontend files) and server (for backend).
- Create 'index.html' inside the
public folder with the frontend code provided above.
- Create 'server.js' inside the
server folder with the backend code provided above.
- Initialize a new Node.js project inside the root of your project folder:
npm init -y
- Install necessary packages:
npm install express multer node-fetch form-data
- Run the server:
node server/server.js
- Open your browser and navigate to
http://localhost:3000 to see the file uploader.
Note:
- Replace
'your-cloudflare-account-id', 'your-cloudflare-auth-email', 'your-cloudflare-auth-key', and 'your-bucket-name' with your actual Cloudflare R2 details.
- The server code does not save the file locally; it directly streams it to Cloudflare R2.
- You may want to use environment variables to store your API keys securely.
- For production, error handling should be more sophisticated and include proper logging.
- The upload URL assumes a public Cloudflare R2 bucket with a custom domain set up. Adjust accordingly.
Remember to read Cloudflare R2's documentation regarding permissions, CORS, and public access settings to ensure your files are accessible as intended.