fs.writefile丢失图像数据

问题描述

我使用发布请求上传图片并将图像数据存储在服务器中,但是丢失了一些图像数据:

let storePic = function(imgData) {
    const base64Data = imgData.replace(/^data:image\/\w+;base64,/,"");
    const dataBuffer = new Buffer.alloc(5000,base64Data,'base64')
        
    fs.writeFile(imgPath,dataBuffer,(err) => {
        if (err) {
            console.log('fail to store image')
        } else {
            console.log('success to store image')
        }
    })
}

当我从服务器上获取图像时,它已损坏:

1

解决方法

应使用Buffer.from(base64Data,'base64')代替,否则将其截断。

Imo可以更好地匹配图像,而不是只是在那里假设它:

let matches = imgData.match(/^data:([A-Za-z-+\/]+);base64,(.+)$/)

if (matches.length !== 3) new Error('Invalid base64 image URI')

// matches[1] contains the mime-type which is handy for alot of things

fs.writeFile(imgPath,Buffer.from(matches[2],'base64'),(err) => {