保存使用画布创建的带有multer的图像



我目前正在尝试保存与画布创建的multer的图像,但我不能让它工作我的代码看起来像这样

const canvas = createCanvas(1000, 1000)
let layout = canvas.getContext('2d')
const image= new Image()
(async () => {
image= await (loadImage(arrayOfImages[randomImage[0]].image_file)) <----- image_file is the file path
}
const img = canvas.toDataURL()
const data = img.replace(/^data:image/w+;base64,/, "");
const buf = Buffer.from(data, "base64");
console.log("this is my buf---------------->", buf)
// this is my buf----------------> <Buffer 89 50 4e 47 0d 0a 1a 0a 00 00 00 0d 49 48 44 52 00 00 03 e8 00 00 03 e8 08 06 00 00 00 4d a3 d4 e4 00 00 00 06 62 4b 47 44 00 ff 00 ff 00 ff a0 bd a7 ... 3925 more bytes>
const storage = multer.memoryStorage()
const upload_image = multer({storage: storage});
upload_image.array(buf)
谁能帮帮我,因为我找不到合适的方法来解决我的问题。我检查了文档,没有找到任何有用的东西

将您的图像从DataURL转换为blob

const dataURItoBlob = function(dataURI : string) {
// convert base64/URLEncoded data component to raw binary data held in a string
var byteString : string;
if (dataURI.split(',')[0].indexOf('base64') >= 0)
byteString = atob(dataURI.split(',')[1]);
else
byteString = unescape(dataURI.split(',')[1]);
// separate out the mime component
var mimeString = dataURI.split(',')[0].split(':')[1].split(';')[0];
// write the bytes of the string to a typed array
var ia = new Uint8Array(byteString.length);
for (var i = 0; i < byteString.length; i++) {
ia[i] = byteString.charCodeAt(i);
}
return new Blob([ia], {type:mimeString});
}

然后上传带有formdata的blob

const file = dataURItoBlob(canvas.toDataURL())
const form = new FormData()
form.append('file',file)

最新更新