如何解决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')
}
})
}
当我从服务器上获取图像时,它已损坏:
解决方法
应使用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) => {
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。