Search code examples
javascriptnode.jsjsonmulter

problem with the image url in json file after using multer to upload image in nodejs


I am using multer to upload image for my blog website after uploading image using postman it returns filename of image into data.json file with "uploads\". How can i get "uploads/" instead of "uploads\" in data.json file ?

data.json

{
        "id": "1610726046543",
        "title": "title",
        "content": "content",
        "post_image": "uploads\\post-image-1610726046051.jpg",
        "added_date": "1610726046543"
}

This is app.js file through which i am getting info about new post using Postman API app and adding this new data into data.json file

app.js

const express = require("express");
const app = express();

const Post = require("./api/models/posts")
const postsData = new Post();

const multer = require('multer')
const storage = multer.diskStorage({
    destination: function (req, file, cb) {
        cb(null, './uploads')
    },
    filename: function(req, file, cb) {
        cb(null, `${file.fieldname}-${Date.now()}.jpg`)
    }
})

const getExt = (mimetype) => {
    switch(mimetype){
        case "image/png":
            return '.png';
        case "image/jpeg":
            return '.jpg';
    }
}

var upload = multer({ storage: storage })

app.use((req, res, next)=>{
    res.setHeader("Access-Control-Allow-Origin","*")
    next()
})

app.use(express.json())
app.use('/uploads', express.static('uploads'))

app.get("/api/posts", (req, res)=>{
    res.status(200).send(postsData.get())
})

app.get("/api/posts/:post_id", (req, res)=>{
    const postId = req.params.post_id
    const foundPost = postsData.getIndividualBlog(postId)
    if(foundPost) {
        res.status(200).send(foundPost)
    }else{
        res.status(404).send("Not Found")
    }
})

app.post("/api/posts", upload.single("post-image"), (req,res)=>{
    const newPost = {
        "id": `${Date.now()}`,
        "title": req.body.title,
        "content": req.body.content,
        "post_image": req.file.path,
        "added_date": `${Date.now()}`
    }
    postsData.add(newPost)
    res.status(201).send(newPost)
})

app.listen(3000, ()=>console.log("Listening on http://localhost:3000"));

Solution

  • Just simply replace it ?

    app.post("/api/posts", upload.single("post-image"), (req,res)=>{
        const newPost = {
            "id": `${Date.now()}`,
            "title": req.body.title,
            "content": req.body.content,
            "post_image": req.file.path.replace("\\", "/"),
            "added_date": `${Date.now()}`
        }
        postsData.add(newPost)
        res.status(201).send(newPost)
    })