gpt4 book ai didi

javascript - 如何将捕获的照片(从浏览器 - Canvas )上传到 Node 服务器?

转载 作者:行者123 更新时间:2023-12-01 00:49:24 25 4
gpt4 key购买 nike

我想将 Canvas 中捕获的照片从 JavaScript 中的浏览器上传到 NodeJS 服务器。我没有得到正确的方法。请帮忙。非常感谢。

(function(){
var video=document.getElementById('video'),
canvas = document.getElementById('canvas'),
vendorUrl = window.URL || window.webkitURL;
context = canvas.getContext('2d');
//photo = document.getElementById('photo');
navigator.getMedia = navigator.getUserMedia ||
navigator.webkitGetUserMedia ||
navigator.mozGetUserMedia ||
navigator.msGetUserMedia;
navigator.getMedia({
video: true,
audio: false
}, function(stream){
video.srcObject=stream;
video.play();
}, function(error){

});
document.getElementById('capture').addEventListener('click',function(){
context.drawImage(video,0,0,400,300);
// photo.setAttribute('src',canvas.toDataURL('image/png'));
download();
});
})();
function download() {
var download = document.getElementById("capture");
var image = document.getElementById("canvas").toDataURL("image/png")
.replace("image/png", "image/octet-stream");
download.setAttribute("href", image);
//download.setAttribute("download","archive.png");
}

此代码可以很好地下载捕获的图像,但我无法将相同的图像上传到 Node 服务器。

最佳答案

这是答案代码。

在客户端

function covertImage() {
var image = document.getElementById("canvas").toDataURL("image/png");
sendMessage(image);
}

//Sending image data to server
function sendMessage(image){
var msg = JSON.stringify(image);
var xhr = new XMLHttpRequest();
xhr.open('POST', true);
xhr.send(msg);
alert('file is saved');
}

在服务器端

http.createServer(function (request, response) {
var post='';
if (request.method == 'POST') {
var body = '';
request.on('data', function (data) {
body += data;
});
request.on('end', function () {
//-------------parsing data from json to string-------------------------
post = JSON.parse(body);
var data = post.replace(/^data:image\/\w+;base64,/, "");
var buf = Buffer.from(data, 'base64');
writeFileToSystem(buf);
});
}

//----------saving image to server side folder------------------
function writeFileToSystem(buf)
{
fs.writeFile("images/image.png", buf, function(err) {
console.log("The file was saved!");
});
}

}

关于javascript - 如何将捕获的照片(从浏览器 - Canvas )上传到 Node 服务器?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57110368/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com