简体   繁体   English

fs.writefile() 丢失图像数据

[英]fs.writefile() lost data of image

I use a post request to upload a picture and store the image data in my server but lost some image data:我使用 post 请求上传图片并将图像数据存储在我的服务器中,但丢失了一些图像数据:

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

When I get the image from the server, it is broken:当我从服务器获取图像时,它坏了:

1

Should use Buffer.from(base64Data, 'base64') instead else its truncated.应该使用Buffer.from(base64Data, 'base64')而不是它被截断。

Imo its slightly better to match out the image rather then just presume its there: 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) => {

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM