Send Blob File from html form to express server so it can be uploaded to cloud

Viewed 957

So I'm trying to make the html form:

<form action="blahblah" encblah="multipart/form-data" whatever>

Thats not the problem, I need to make that form send the blob to express

app.post('/upload/avatars', async (req, res) => {
  const body = req.body;
  console.log(req.file);
  console.log(body);
  res.send(body);
});

So I can access the blob, create a read stream, pipe it to the cloud, and bam, upload the file without downloading anything on the express server it self.

Is that possible? If yes, please tell me how. If no, please tell me other alternatives.

2 Answers

On the client we do a basic multi-part form upload. This example is setup for a single image but you could call uploadFile in sequence for each image.

//client.ts

const uploadFile = (file: File | Blob) => {
  const formData = new FormData();
  formData.append("image", file);
  return fetch("/upload", {
    method: "post",
    body: formData,
  });
};

const handleUpload = (event: any) => {
  return event.target.files.length ? uploadFile(event.target.files[0]) : null;
};

On the server we can use multer to read the file without persisting it to disk.

//server.js
const express = require("express");
const app = express();

const multer = require("multer");
const upload = multer();

app.post(
  "/upload",
  upload.fields([{ name: "image", maxCount: 1 }]),
  (req, res, next) => {
    console.log("/upload", req.files);
    if (req.files.image.length) {
      const image = req.files.image[0]; // { buffer, originalname, size, ...}
      // Pipe the image.buffer where you want.
      res.send({ success: true, count: req.files.image.originalname });
    } else {
      res.send({ success: false, message: "No files sent." });
    }
  }
);

For larger uploads I recommend socket.io, but this method works for reasonably sized images.

  1. it is possible, but when you have a lot of traffic it would overwhelm your express server (in case you are uploading videos or big files ) but if it's for uploading small images (profile image, etc...) you're fine. either way you can use Multer npm

  2. I'd recommend using client-side uploading on ex: s3-bucket, etc..., which returned a link, and therefore using that link.

Related