Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to upload image from img tag?

I am trying to upload photo to server form img tag, but i can't do it. plz help. First I take photo from webcam, then i want to upload on my web server. When I Snap photo from webcam, it show on the screen by javascript method getelementbyId. Now I want to code that it will be uploaded to my web server. Plz Help Thanks in advance..... My Code is below:

//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>
like image 715
Irfan Gondal Avatar asked Oct 16 '16 06:10

Irfan Gondal


1 Answers

<img> is an html element. The data URI that you created at created at var dataURL = picture.toDataURL(); is an image file.

You can POST the data URI that you created to server using 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);
like image 137
guest271314 Avatar answered Oct 02 '22 12:10

guest271314