0
我正在嘗試做一個小應用程序,讓用戶使用其攝像頭拍照並將該圖片發送到服務器,以便將其存儲爲.png文件。現在幾乎所有工作都正常,您可以使用相機拍攝照片,然後發送表單,然後創建一個.png文件,但它看起來是無效的,而不是圖像。我在這段代碼中錯過了什麼嗎?使用node.js通過畫布dataURL從網絡攝像頭保存.png圖片時無效的文件
在此先感謝。
這是前端代碼:
window.addEventListener("DOMContentLoaded", function() {
var canvas = document.getElementById("canvas"),
context = canvas.getContext("2d"),
video = document.getElementById("video"),
videoObj = { "video": true },
errBack = function(error) {
console.log(error.code);
};
// Put video listeners into place
if(navigator.getUserMedia) {
navigator.getUserMedia(videoObj, function(stream) {
video.src = stream;
video.play();
}, errBack);
} else if(navigator.webkitGetUserMedia) {
navigator.webkitGetUserMedia(videoObj, function(stream){
video.src = window.webkitURL.createObjectURL(stream);
video.play();
}, errBack);
}
else if(navigator.mozGetUserMedia) {
navigator.mozGetUserMedia(videoObj, function(stream){
video.src = window.URL.createObjectURL(stream);
video.play();
}, errBack);
}
// Trigger photo snap
document.getElementById("snap").addEventListener("click", function() {
context.drawImage(video, 0, 0, 640, 480);
var dataURL = canvas.toDataURL('image/png').replace(/^data:image\/png;base64,/,'');
var imginput = document.getElementById('imgdata');
imginput.value = dataURL;
});
}, false);
這是Node.js的服務器上的代碼:
// Load modules/dependencies
var http = require('http');
var fs = require('fs');
var qs = require('querystring');
var config = JSON.parse(fs.readFileSync('config.json'));
var port = config.port;
var server = http.createServer(function(request, response) {
console.log('Received request: ' + request.url);
fs.readFile('./' + request.url, function(error, data) {
if (error) {
response.writeHead(404, {'Content-type':'text/plain'});
response.end('Sorry the page was not found');
} else if (request.method == 'POST') {
processPost(request, response, function() {
console.log(response.post);
response.writeHead(200, "OK", {'Content-Type': 'text/plain'});
response.end();
});
} else {
response.writeHead(200, {'Content-type':'text/html'});
response.end(data);
};
})
});
function processPost(request, response, callback) {
var queryData = "";
if(typeof callback !== 'function') return null;
if(request.method == 'POST') {
request.on('data', function(data) {
queryData += data;
fs.writeFile('image.png', queryData, 'base64');
});
request.on('end', function() {
callback();
});
} else {
response.writeHead(405, {'Content-Type': 'text/plain'});
response.end();
}
}
server.listen(port, function() {
console.log('Listening ' + port);
});