Alk
Alk

Reputation: 5557

Uploading Image with Multer - additional blob created alongside image

const upload = multer({ dest: `${__dirname}/uploads/images` });

app.post(
  "/api/users/:id/uploadProfilePic",
  upload.single("image"),
  updateProfilePic
);

const updateProfilePic = async (req, res) => {
  const userId = req.param("id");
  if (userId && isNumber(userId)) {
    // When using the "single"
    // data come in "req.file" regardless of the attribute "name". *
    const tmpPath = req.file.path;

    // The original name of the uploaded file
    // stored in the variable "originalname". *
    const targetPath = `uploads/images/${req.file.originalname}`;

    /** A better way to copy the uploaded file. **/
    const src = fs.createReadStream(tmpPath);
    const dest = fs.createWriteStream(targetPath);
    src.pipe(dest);
    src.on("end", () => {
      res.status(200).send("complete");
    });
    src.on("error", err => {
      res.status(500).send(err);
    });
  }
};

In my express app, I have the following code for uploading an image - this seems to upload the image successfully, but it also creates this data blob in my uploads folder - multipart

Upvotes: 0

Views: 487

Answers (1)

Rajat banerjee
Rajat banerjee

Reputation: 1821

You can do something like

const storage = multer.diskStorage({
    destination: function (req, file, cb) {
      cb(null, 'uploads/')
    },
    filename: function (req, file, cb) {
      cb(null, file.originalname)
    }
  })

  const upload = multer({storage: storage})

Upvotes: 1

Related Questions