0

So I'm new to backend and node, and have been working on an app that should also support an image file upload when creating a new item.

I had issues at first getting this error ENOENT: no such file or directory but after following the answers here (I'm using a windows machine and was following a tutorial on a Mac) ENOENT: no such file or directory .?

I've switched to using the __dirname together with path and I have no such error anymore.

What I do face now is another issue:

  1. When I ask for the file.path, it is no longer relative like ./uploads but instead it is the full path on my computer

    C:\Users\myuser\Documents\Coding\travel-market\api\src\uploads\2022-12-05T12-39-35.924Z-Screenshot 2022-11-02 193712.png

So when I pull that new item and try to render the image it doesn't show. Also I get this error Not allowed to load local resource.

Is that ok and would work just fine once the api is actually hosted on a server? Or is there a different way of doing things that would allow me to also view the image while I'm developing locally?

This is my entire code for saving right now:

const storage = multer.diskStorage({
    destination: function(req, file, cb) {
        cb(null, path.join(__dirname, "..", "uploads"));
    },
    filename: function(req, file, cb) {
        const uniqueName =
            new Date().toISOString().replace(/:/g, "-") + "-" + file.originalname;
        cb(null, uniqueName);
    },
});

const fileFilter = function(req, file, cb) {
    if (!file.originalname.match(/\.(jpg|jpeg|png)$/)) {
        return cb(new Error("Please upload an image file"));
    }

    cb(undefined, true);
};

const upload = multer({
    storage,
    limits: {
        fileSize: 1024 * 1024 * 5, // This number is in bytes, so this is 5mb
    },
    fileFilter,
});

// Post a new plan
router.post("/plans", auth, upload.single("plan_image"), async(req, res) => {
    console.log("this is the file", req.file);
    const details = JSON.parse(req.body.details);
    console.log("this is the body", details);

    const plan = new Plan({
        ...details,
        image: req.file.path,
        author: req.user._id,
    });

    try {
        await plan.save();
        res.status(201).send(plan);
    } catch (e) {
        console.log("failed to save", e);
        res.status(400).send(e);
    }
});
Tsabary
  • 3,119
  • 2
  • 24
  • 66

1 Answers1

0

You can just configure multer like this

const upload = multer({dest:'uploads/'});

Here I am saving my files to the upload folder. This will grab the relative path like "uploads/filename" instead of the full path.

The problem with windows is that, it specifies the path with "\" character which will cause the multer api to pick the path like this - "uploads\filename" but it should work fine in a server since in Unix based system like Mac and Linux the path is specified with "/".