[英]Send canvas.toDataURL images to nodejs
我正在尝试将图像从前端脚本发送到我的服务器。
前端脚本:
var img_data = canvas.toDataURL('image/jpg'); // contains screenshot image
// Insert here POST request to send image to server
我正在尝试接受后端的数据并将其存储到 req.files 中以便能够像这样访问:
const get_image = (req, res) => {
const File = req.files.File.tempFilePath;
}
我该怎么做才能将图像发送到服务器并像上面的示例一样获取图像?
您的img_data
是一个 base 64 字符串,您可以在 post 请求中直接将其发送到服务器
例如
await fetch('/api/path', { method: 'POST', headers: { "content-type": "application/json"}, body: JSON.stringify({ file: img_data }) });
在您的后端,您可以将此字符串转换为二进制,并保存到文件中。
var fs = require('fs');
app.post('/api/path', async (req, res) => {
const img = req.body.file;
var regex = /^data:.+\/(.+);base64,(.*)$/;
var matches = string.match(regex);
var ext = matches[1];
var data = matches[2];
var buffer = Buffer.from(data, 'base64'); //file buffer
.... //do whatever you want with the buffer
fs.writeFileSync('imagename.' + ext, buffer); //if you do not need to save to file, you can skip this step.
....// return res to client
})
您必须先将其转换为 Blob,然后 append 将其转换为 Form。 表单将是您发送到服务器的请求的主体。
canvas.toBlob(function(blob){
var form = new FormData(),
request = new XMLHttpRequest();
form.append("image", blob, "filename.png");
request.open("POST", "/upload", true);
request.send(form);
}, "image/png");
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.