【问题标题】:Return URL of locally stored image [Node JS API]返回本地存储图像的 URL [Node JS API]
【发布时间】:2021-10-04 21:12:09
【问题描述】:

我正在创建一个接收 base64 字符串的 API,将其转换为图像 [label.jpeg],然后返回图像的 URL。现在我被困在如何创建本地图像的 URL 以便可以公开访问。

下面是我的代码,目标是在调用 API 时返回 'label.jpeg' 的 URL 地址。

// Post base64 string
app.post('/post-base64', (req, res) => {

    // Captured img [base64 string]
    let strBase64 = req.body
    console.log(strBase64)

    // Convert base64 --> img.jpeg
    let buffer = Buffer.from(strBase64, 'base64')
    console.log(buffer)

    // Write base64 to file
    let writeStream = fs.createWriteStream('label.txt')
    writeStream.write(buffer, 'base64')


    writeStream.on('finish', () => {
        console.log('WROTE ALL!')
    })

    writeStream.end()

    // Save img as 'label.jpeg'
    fs.writeFileSync('label.jpeg', buffer)

    res.send({
        // TOD0: Return label.jpeg link
    })
})

谢谢。

【问题讨论】:

    标签: javascript node.js express fs


    【解决方案1】:

    您可以将上传的图像存储在您为staticallyexpress.static 提供服务的“公共”文件夹中。比如:

    // add this to your app.js
    app.use(express.static('public'))
    
    // store uploaded image in the public folder
    app.post(..) => {
       // ... note that you should probably switch
       // to the non-blocking version e.g. fs.promises.writeFile(...)
       fs.writeFileSync(__dirname + '../public/name-of-img.jpeg', buffer)
    })
    

    Express 现在将负责提供文件,因此图像的 URL 将只是 http://yourhostname/name-of-img.jpeg

    【讨论】:

    • fs.writeFileSync 在这里不好,当上传运行时你会阻塞整个事件循环。
    • 是的,但它与 OP 的问题没有直接关系。不过我会在评论中留下提示;)
    • 实际上我的代码上方确实有这个app.use('/static', express.static(path.join(__dirname, 'public')))。那么,img 的 URL 应该是http://localhost:2000/static/label.jpeg 对吧?但我无法得到 img,得到 404 错误。你能解释一下非阻塞版本吗?不过。
    • 路径看起来没问题,但是您在存储文件时是否使用了公用文件夹的正确相对路径(例如../public/<filename>)?关于为什么你不应该使用同步版本......这个已经被问过很多次了,例如:stackoverflow.com/questions/17604866/…
    猜你喜欢
    • 1970-01-01
    • 2015-04-04
    • 2019-02-05
    • 1970-01-01
    • 2021-09-01
    • 1970-01-01
    • 2021-07-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多