Cloud storage lets your app save files online instead of on one computer. This helps share files easily and keeps them safe.
Cloud storage integration concept in Express
Start learning this pattern below
Jump into concepts and practice - no test required
const cloudStorage = require('cloud-storage-sdk'); const storageClient = cloudStorage.createClient({ apiKey: 'your-api-key', bucketName: 'your-bucket-name' }); app.post('/upload', (req, res) => { const file = req.file; // from middleware like multer storageClient.upload(file.path, file.originalname) .then(() => res.send('File uploaded!')) .catch(err => res.status(500).send('Upload failed')); });
Replace 'cloud-storage-sdk' with the actual SDK for your cloud provider (like AWS S3, Google Cloud Storage, Azure Blob Storage).
Use middleware like multer to handle file uploads from users before sending to cloud storage.
const AWS = require('aws-sdk'); const fs = require('fs'); const s3 = new AWS.S3({ region: 'us-east-1' }); app.post('/upload', (req, res) => { const file = req.file; const params = { Bucket: 'my-bucket', Key: file.originalname, Body: fs.createReadStream(file.path) }; s3.upload(params, (err, data) => { if (err) return res.status(500).send('Upload error'); res.send('Uploaded to ' + data.Location); }); });
const { Storage } = require('@google-cloud/storage');
const storage = new Storage();
const bucket = storage.bucket('my-bucket');
app.post('/upload', async (req, res) => {
const file = req.file;
await bucket.upload(file.path, { destination: file.originalname });
res.send('File uploaded to Google Cloud Storage');
});This Express app lets users upload a file via a POST request to '/upload'. It uses multer to handle the file upload, then sends the file to AWS S3 cloud storage. After uploading, it deletes the temporary local file and sends a success message with the file URL.
const express = require('express'); const multer = require('multer'); const AWS = require('aws-sdk'); const fs = require('fs'); const app = express(); const upload = multer({ dest: 'uploads/' }); const s3 = new AWS.S3({ region: 'us-east-1' }); app.post('/upload', upload.single('file'), (req, res) => { const file = req.file; const params = { Bucket: 'my-bucket', Key: file.originalname, Body: fs.createReadStream(file.path) }; s3.upload(params, (err, data) => { fs.unlinkSync(file.path); // remove temp file if (err) { return res.status(500).send('Upload failed'); } res.send(`File uploaded successfully to ${data.Location}`); }); }); app.listen(3000, () => console.log('Server running on port 3000'));
Always secure your API keys and never expose them in frontend code.
Clean up temporary files after uploading to avoid filling disk space.
Check your cloud storage permissions to allow uploads from your app.
Cloud storage helps save and share files online safely.
Use Express with middleware like multer to handle file uploads.
Use cloud provider SDKs to send files from your server to the cloud.
Practice
Solution
Step 1: Understand cloud storage role
Cloud storage is used to save files online so they can be accessed safely from anywhere.Step 2: Relate to Express app integration
Integrating cloud storage with Express allows the app to upload and store files securely in the cloud.Final Answer:
To save and share files online safely -> Option DQuick Check:
Cloud storage = safe online file saving [OK]
- Thinking cloud storage speeds up server response
- Confusing cloud storage with routing features
- Assuming cloud storage is for local logs
Solution
Step 1: Identify middleware for file uploads
Multer is a popular Express middleware designed specifically to handle multipart/form-data, which is used for uploading files.Step 2: Confirm other options' roles
Cors handles cross-origin requests, body-parser parses JSON or urlencoded data, helmet adds security headers. None handle file uploads.Final Answer:
multer -> Option CQuick Check:
File upload middleware = multer [OK]
- Choosing cors for file uploads
- Confusing body-parser with file upload handling
- Selecting helmet which is for security headers
const upload = multer({ dest: 'uploads/' });
app.post('/upload', upload.single('file'), async (req, res) => {
const params = { Bucket: 'mybucket', Key: req.file.filename, Body: fs.createReadStream(req.file.path) };
await s3.upload(params).promise();
res.send('Upload successful');
});Solution
Step 1: Analyze multer usage
Multer saves the uploaded file to 'uploads/' and adds file info to req.file, so req.file.filename and req.file.path exist.Step 2: Check AWS upload call
The s3.upload call uses the file stream correctly and awaits the promise, so if AWS credentials are correct, upload succeeds.Final Answer:
Upload successful -> Option BQuick Check:
Correct multer + AWS upload = success message [OK]
- Assuming syntax error due to async/await
- Forgetting multer adds req.file
- Ignoring AWS credentials setup
app.post('/upload', upload.single('file'), (req, res) => {
const bucket = storage.bucket('mybucket');
bucket.upload(req.file.path, (err, file) => {
if (err) res.status(500).send('Upload error');
});
res.send('File uploaded');
});Solution
Step 1: Check asynchronous upload call
bucket.upload is asynchronous with a callback, but res.send is called immediately after, not waiting for upload to finish.Step 2: Understand response timing
Sending response before upload completes can cause wrong success message even if upload fails.Final Answer:
Missing await or callback handling before sending response -> Option AQuick Check:
Async upload must finish before response [OK]
- Sending response immediately without waiting
- Assuming bucket name syntax is wrong
- Confusing single vs array upload middleware
const upload = multer({ dest: 'uploads/' });
app.post('/upload-multiple', upload.array('files'), async (req, res) => {
const urls = [];
for (const file of req.files) {
const blobClient = containerClient.getBlockBlobClient(file.filename);
await blobClient.uploadFile(file.path);
urls.push(blobClient.url);
}
res.json({ uploadedUrls: urls });
});Solution
Step 1: Check multer usage for multiple files
upload.array('files') correctly handles multiple files and stores them in req.files array.Step 2: Analyze upload loop and response
The for loop uses await to upload each file sequentially, pushes each URL to the urls array, then sends JSON response with all URLs.Final Answer:
Uploads files sequentially, collects URLs, then responds with JSON list -> Option AQuick Check:
Sequential upload + URL collection = correct response [OK]
- Using upload.single for multiple files
- Responding before uploads finish
- Forgetting to collect URLs in array
