đFile serving backend
The Obfuscated image , had to be attached to url field of the NFT struct , now there were two ways to do it either use a proper url or a base64 encoding , the first attempt was using the base64 encoding but it gave the JSON RPC error that the byte array Vector<u8> could not take more than 16384 , which meant that images with approximately 125 x 125 pixels were the max possible size that could be succesfully shown this way . So now we use the second approach here to get a url from a server deployed on render
Below is the complete Express + Multer
upload service and a moderately detailed explanation of how it works, along with why it was needed in your NFT project. The code itself is quite self-explanatory and just a normal server , which does need much understanding
const express = require('express');
const multer = require('multer');
const path = require('path');
const fs = require('fs');
const cors = require('cors');
const app = express();
// Enable CORS for frontend requests
app.use(cors());
const PORT = 3000;
// Ensure uploads folder exists
const uploadDir = path.join(__dirname, 'uploads');
if (!fs.existsSync(uploadDir)) {
fs.mkdirSync(uploadDir);
}
// Multer storage config
const storage = multer.diskStorage({
destination: function (req, file, cb) {
cb(null, uploadDir);
},
filename: function (req, file, cb) {
const uniqueName = Date.now() + '-' + file.originalname;
cb(null, uniqueName);
}
});
// Filter for .jpeg, .jpg, .png
const fileFilter = (req, file, cb) => {
const allowedTypes = ['image/jpeg', 'image/jpg', 'image/png'];
if (allowedTypes.includes(file.mimetype)) {
cb(null, true);
} else {
cb(new Error('Only .jpeg, .jpg, and .png files are allowed!'), false);
}
};
const upload = multer({ storage, fileFilter });
// Serve static files from /uploads
app.use('/uploads', express.static(uploadDir));
// Upload endpoint
app.post('/upload', upload.single('image'), (req, res) => {
if (!req.file) {
return res.status(400).json({ error: 'No file uploaded or invalid file type' });
}
const fileUrl = `${req.protocol}://${req.get('host')}/uploads/${req.file.filename}`;
res.json({ url: fileUrl });
});
// Start server
app.listen(PORT, () => {
console.log(`Server running at http://localhost:${PORT}`);
});
Last updated