我正在尝试通过 img 标签将照片上传到服务器,但我做不到。请帮助。 首先我从网络摄像头拍照,然后我想上传到我的网络服务器上。当我从网络摄像头拍摄照片时,它通过 javascript 方法 getelementbyId 显示在屏幕上。现在我想编写代码将其上传到我的网络服务器。 请帮忙提前致谢..... 我的代码如下:
//script_photo.js
var photoButton = document.getElementById('snapPicture');
photoButton.addEventListener('click', picCapture, false);
navigator.getUserMedia ||
(navigator.getUserMedia = navigator.mozGetUserMedia ||
navigator.webkitGetUserMedia || navigator.msGetUserMedia);
if (navigator.getUserMedia) {
navigator.getUserMedia({video:true,audio:false}, onSuccess, onError);
} else{
alert('Your browser isnt supported');
}
function onSuccess(stream) {
vidContainer = document.getElementById('webcam');
var vidStream;
if (window.webkitURL){
vidStream = window.webkitURL.createObjectURL(stream);
}else{
vidStream = stream;
}
vidContainer.autoplay = true;
vidContainer.src = vidStream;
}
function onError(){
alert('Houston, we have a problem');
}
function picCapture(){
var picture = document.getElementById('capture'),
context = picture.getContext('2d');
picture.width = "600";
picture.height = "400";
context.drawImage(vidContainer, 0, 0, picture.width, picture.height);
var dataURL = picture.toDataURL();
document.getElementById('canvasImg').src = dataURL;
}
<!DOCTYPE>
<html>
<head>
<title>My Photo Booth</title>
<head>
<body>
<center>
<video id="webcam" width="200" height="200"></video>
<br>
<input type="button" id="snapPicture" value="Snap A Picture!" />
<p>
<canvas id="capture" style="display:none;"></canvas>
<img id="canvasImg" alt="right click to save">
<script src = "script_photo.js"></script>
</center>
</body>
</html>
最佳答案
<img>
是一个 html
元素。 data URI
您创建于 var dataURL = picture.toDataURL();
是图片文件。
您可以 POST
data URI
您使用 XMLHttpRequest()
创建到服务器的, FormData()
.
var request = new XMLHttpRequest();
request.open("POST", "/path/to/server", true);
var data = new FormData();
data.append("image", dataURL, "imagename");
request.send(data);
关于javascript - 如何从 img 标签上传图片?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40067544/