【问题标题】:Saving Images from Client Side using API使用 API 从客户端保存图像
【发布时间】:2020-06-08 13:02:50
【问题描述】:

我有一个正在重写的网站。网站的博客区域有一张特色图片 - 我正在尝试找出保存图片的最佳方法。

我遵循了一个使用 mongoose 中的 file.mv() 函数的教程(我认为来自 mongoose?也许是快递?) - 无论哪种方式,它都会将图像移动到我的公共文件夹内的文件夹中。

它可以在开发服务器上运行,但是当我推送到 Heroku 时,它就不行了。我确信这与文件位置有关。

我不知道我是否以传统方式这样做......但基本上我让博客作者上传图片并写帖子。然后我将帖子内容保存到我的 bongo db。文件位置保存在特色图像下,而不是整个图片保存在特色图像下。这样我就不必将图像上传到数据库。

欢迎任何建议!谢谢!

这里是代码

    //save images
blogRouter.post('/upload', (req, res) => {
    if(req.files === null ){
        return res.status(400).json({ msg: 'No file uploaded'})
    }

    const file = req.files.file;
    const fileName = file.name.replace(/\s+/g, '');

    file.mv(`${__dirname}/../client/public/BlogImgs/${fileName}`, err => {
        if(err){
            console.error(err)
            return res.status(500).send(err);
        }

        res.json({ fileName: fileName, filePath: `/BlogImgs/${fileName}`});
    })
})

//Post New Blog
blogRouter.post('/', (req, res) => {
    let newBlog = new blog({
        title: req.body.title,
        content: req.body.content,
        author: req.body.author,
        comments: req.body.comments,
        featuredImg: req.body.featuredImg,
        summary: req.body.summary
    })
    newBlog.save().then(item => res.json(item))
})

【问题讨论】:

    标签: javascript image api express


    【解决方案1】:

    您不需要将其存储在数据库中,只需将其名称存储在服务器上的文件夹中即可,您可以使用multer 进行图像上传。

    【讨论】:

      猜你喜欢
      • 2017-12-16
      • 2017-08-04
      • 2016-02-15
      • 1970-01-01
      • 1970-01-01
      • 2012-04-27
      • 1970-01-01
      • 1970-01-01
      • 2012-03-12
      相关资源
      最近更新 更多