Documentation

Processing Client-side Uploads

Let’s suppose you have a simple form with file HTML Element.

<form action="/upload" method="post">
  <input type="file" name="file" />
  <button type="submit">Upload</button>
</form>

Here’s how to handle the /upload endpoint in a Node.js backend. This example uses Express.js, but the logic can be easily adapted to other frameworks with minimal changes.

Dependencies

npm install express multer

Code

import express from 'express';
import multer from 'multer';
import path from 'path';
import fs from 'fs';

const app = express();

const storage = multer.memoryStorage();
const upload = multer({ storage });

// Endpoint to handle upload
app.post('/upload', upload.single('file'), (req, res) => {
  if (!req.file) {
    return res.status(400).json({ error: 'No file uploaded' });
  }

  // See: https://magecdn.com/docs/uploading-images-rest-api
  const form = new FormData();
  form.append("file", req.file.buffer, req.file.originalname);
  form.append("path", "/uploads");

  // See: https://magecdn.com#dd/docs/authentication
  const response = await fetch("https://api.magecdn.com/upload?token=YOUR_API_TOKEN", {
    method: "POST",
    headers: form.getHeaders(),
    body: form,
  });

  if (!response.ok) {
    const errBody = await response.text();
    return res.status(response.status).send("Upload failed: " + errBody);
  }

  const json = await response.json();
  res.redirect(json.url);
  
});

// Start the server
app.listen(3000, () => {
  console.log('Server running at http://localhost:3000');
});

Uploading Local Files (Using fetch and buffer)

import fs from "fs";
import path from "path";

const filePath = "./abc.jpg";
const fileName = path.basename(filePath);

const fileBuffer = fs.readFileSync(filePath);
const form = new FormData();

form.append("file", new Blob([fileBuffer]), fileName);
form.append("path", "/uploads");

const response = await fetch("https://api.magecdn.com/upload?token=YOUR_API_TOKEN", {
  method: "POST",
  headers: form.getHeaders(),
  body: form,
});

if (!response.ok) {
  const errBody = await response.text();
  return res.status(response.status).send("Upload failed: " + errBody);
}

const json = await response.json();
res.redirect(json.url);