【问题标题】:problem with the image url in json file after using multer to upload image in nodejs使用multer在nodejs中上传图像后,json文件中的图像url出现问题
【发布时间】:2021-01-15 16:42:59
【问题描述】:

在使用邮递员上传图片后,我正在使用 multer 为我的博客网站上传图片,它会将图片的文件名返回到带有“uploads\”的 data.json 文件中。 如何在 data.json 文件中获取“uploads/”而不是“uploads\”?

数据.json

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

这是 app.js 文件,我通过它使用 Postman API 应用程序获取有关新帖子的信息并将这些新数据添加到 data.json 文件中

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"));

【问题讨论】:

  • 您是否在 Windows 中运行您的服务器?似乎是 Windows 和 Unix 之间通常的文件分隔符差异 - 在这种情况下,除了一些解决方法(如搜索替换)之外,通常没什么可做的。如果您不在 Windows 上,那么一定是发生了其他事情。

标签: javascript node.js json multer


【解决方案1】:

只是简单地替换它?

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)
})

【讨论】:

    【解决方案2】:

    我不太了解 node.js 。但是您可以创建一个函数,在帖子完成后将所有“\”替换为“//”。我相信您可以通过首先阅读它然后编辑它来编辑 json:

        JSON.parse(json);
    

    【讨论】:

      猜你喜欢
      • 2021-11-23
      • 2021-01-24
      • 1970-01-01
      • 2023-01-07
      • 2021-02-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多