skip to Main Content

I’m using multer package to let visitors upload their images. everything works fine but in the end the path to the image is something like this :

"/imagesthe-picture.jpg "

even in the database (I’m using mongodb) the path is saved like this

imageurl: imagesthe-picture.jpg

I’m using this middleware to give the multer proper filter :

const fileStorage = multer.diskStorage({
  destination: (req, file, cb) => {
    cb(null, "images/");
  },
  filename: (req, file, cb) => {
    cb(null, Math.round(Math.random() * 100000) + "-" + file.originalname);
  },
});

const fileFilter = (req, file, cb) => {
  if (
    file.mimetype === "image/png" ||
    file.mimetype === "image/jpg" ||
    file.mimetype === "image/jpeg"
  ) {
    cb(null, true);
  } else {
    cb(null, false);
  }
};

app.use(multer({ storage: fileStorage, fileFilter: fileFilter }).single("image"));

and in the controller I simply get the path to file :

const imageurl = image.path

Do I need to fix this url problem or I can ignore this?

2

Answers


  1. The issue you’re encountering with the file path containing both forward slash ("/") and backslash ("") characters is likely due to platform differences. Forward slashes are commonly used in Unix-based systems (such as Linux), while backslashes are used in Windows-based systems.

    To ensure consistent and portable file paths, it’s generally recommended to use forward slashes ("/") as the path separator, regardless of the operating system. In your case, you can update the file path to use forward slashes before saving it to the database. Additionally, when retrieving the file path from the database, you can replace any backslashes with forward slashes to ensure consistency.

    Here’s an example of how you can achieve this in JavaScript:

    const imagePath = 'images\the-picture.jpg'; // example file path with backslashes
    const normalizedPath = imagePath.replace(/\/g, '/'); // replace backslashes with forward slashes
    console.log(normalizedPath); // prints: images/the-picture.jpg
    

    By normalizing the file path to use forward slashes consistently, you can avoid potential issues related to different file path representations across different platforms.

    Login or Signup to reply.
  2. yes, you can do it that way according to my knowledge but then you will have to implement the "/" check for error free code, either on back-end or, front-end.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search