简体   繁体   English

如何保存来自 multer memory 磁盘的图像?

[英]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:我在 nodejs 中使用 multer 来处理 multipart/formdata 请求并获取请求中的图像文件,如下所示:

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?如何从req.file生成图像然后上传而不将其保存在磁盘上?

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. 此处dropbox 提供的示例代码,读取utf-8中的文件并上传。

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.您也可以通过将发布数据中的缓冲区编码为utf-8然后上传该缓冲区,同时将其保存在 memory 中并且永远不必接触磁盘。

  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" });
  }
);


声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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