简体   繁体   中英

How to save image coming from multer memory disk?

I use multer in nodejs to handle multipart/formdata request and get the image file on the request like this:

import multer from "multer";

const upload = multer({
  storage: multer.memoryStorage(),
  limits: { fileSize: 1000000000, files: 2 },
});



app.post("/", upload.single("image"), (req, res , next) => {
      const imageFile = req.file

      dbx
        .filesUpload({ path: "/image.png", contents: imageFile })
        .then((response: any) => {
         
        })
        .catch((uploadErr) => {
         
        });
    }
  )

The problem is I can't upload the image and it gives me error that it's a Buffer not an actual image. How can I generate the image from req.file then upload it without saving it on the disk?

You can decode your data or change it's encoding but to convert it to an image doesn't make any sense.

The example code provided by dropbox here , reads a file in utf-8 and uploads it.

You can also do that same by taking the buffer in the post data encoding it as utf-8 then uploading that while keeping it in memory and never have to touch disk.

  const imageFile = req.file.buffer.toString('utf-8');

I solved the issue by sending the buffer image itself to dropbox like this:

app.post(
  "/",
  upload.single("image"), // or upload single for one file only
  (req, res) => {
    const imageFile = req.file && req.file.buffer;
    // console.log(imageFile);

    dbx
      .filesUpload({ path: "/life.png", contents: imageFile })
      .then((response: any) => {
        console.log("SUccess");
      })
      .catch((uploadErr) => {
        console.log("ERRRR");
        console.log(uploadErr);
      });

    res.json({ message: "hello" });
  }
);


The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM