make a node.js cloudflare r2 uploader : Bounty Description
What it needs
Front End
Backend
To give the user a url of the uploaded file.
node.js and html in seperate files.
what i dont want and wont reply to
asking for credentials (eg credit card).
copy and paste from internet
begging
asking for price raise.
Assistant
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.
// ./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:
bash
npm init -y
Install necessary packages:
bash
npm install express multer node-fetch form-data
Run the server:
bash
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.