0
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

Alk
  • 5,215
  • 8
  • 47
  • 116
  • Is the screenshot taken before you execute your "copy", from your code it seems like multer did the upload, then you copied it to the same path. – Rajat banerjee Nov 15 '19 at 17:10
  • The Screenshot is from when the code is done executing and code 200 is returned – Alk Nov 15 '19 at 17:12
  • can you comment out all the code inside your handler, and just send back a 200 . – Rajat banerjee Nov 15 '19 at 17:20
  • if I do that it only uploads the blob but not the image - I want the opposite – Alk Nov 15 '19 at 17:27
  • your question is somewhat misleading in that case " this seems to upload the image successfully, but it also creates this data blob in my uploads folder -" – Rajat banerjee Nov 15 '19 at 17:31
  • my code does upload the image successfully - it doesn't upload it if I follow what you said and remove the code in the handler. It is not misleading. – Alk Nov 15 '19 at 17:32
  • Let us [continue this discussion in chat](https://chat.stackoverflow.com/rooms/202426/discussion-between-rajat-banerjee-and-alk). – Rajat banerjee Nov 15 '19 at 17:35

1 Answers1

1

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})
Rajat banerjee
  • 1,781
  • 3
  • 17
  • 35