Getting the image url uploaded in nodejs

Viewed 2874

I am using nodejs multer to upload an image file to image uploads directory. After uploading, how can this particular image be displayed in html img tag in client browser. What is the url?

When I type in http://localhost:3000/uploads/1591342432.jpeg, it says cannot get the file.

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);
  }
});
3 Answers

It seems you are using multer to upload img to a local folder called uploads.

I will recommend the following tutorial: upload img to firebase

This tutorial uses multer to upload the cloud firebase. Once you upload the image, you will get the link to the image where it is stored on the cloud and the same link you can use on the other server

If you haven't already, you will need to set GET path for the image resource when attempting to fetch via http://localhost:3000/1599134489853.jpeg. For an express app, it appears the current simple/preferred method for returning the file is res.sendFile. Otherwise, you can generate stream and return as demonstrated here.

I think I need to set a static directory:

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

Then I can access the image file as:

http://localhost:3000/1599134489853.jpeg
Related