【问题标题】:Getting the image url uploaded in nodejs获取nodejs中上传的图片url
【发布时间】:2020-12-22 16:22:21
【问题描述】:

我正在使用 nodejs multer 将图像文件上传到图像上传目录。上传后,这个特定的图像如何在客户端浏览器的 html img 标签中显示。网址是什么?

当我输入 http://localhost:3000/uploads/1591342432.jpeg 时,它说无法获取文件。

var storage = multer.diskStorage({
  destination: function (req, file, cb) {
    cb(null, "./uploads/");
  },
  filename: function (req, file, cb) {
    cb(null, Date.now() + ".jpeg");
  },
});

const upload = multer({ storage: storage });

router.post("/upload", upload.single("file"), async (req, res) => {
  try {
    console.log("uploading...");
    console.log(req.file.filename);
    res.json({ cool: "yes" });
    // res.json({ file: req.file });
  } catch (error) {
    console.log(error);
  }
});

【问题讨论】:

    标签: javascript node.js multer


    【解决方案1】:

    您似乎正在使用 multer 将 img 上传到名为 uploads 的本地文件夹。

    我会推荐以下教程:upload img to firebase

    本教程使用 multer 上传云 Firebase。上传图片后,您将获得存储在云端的图片的链接以及您可以在其他服务器上使用的相同链接

    【讨论】:

      【解决方案2】:

      如果您还没有设置,则在尝试通过http://localhost:3000/1599134489853.jpeg 获取图像资源时需要设置 GET 路径。对于快速应用程序,当前返回文件的简单/首选方法似乎是res.sendFile。否则,您可以生成流并返回,如 here 所示。

      【讨论】:

        【解决方案3】:

        我想我需要设置一个静态目录:

        app.use(express.static("uploads"));
        

        然后我可以访问图像文件为:

        http://localhost:3000/1599134489853.jpeg
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2017-09-19
          • 2023-04-04
          • 2021-01-24
          • 2021-07-13
          • 2020-03-02
          • 2020-08-04
          • 2017-12-12
          相关资源
          最近更新 更多