Jump to content

Recommended Posts

I have a  webcam script that works successfully on the web page. It starts, records, stops, and plays back successfully,
 
But my Upload portion of the code needs help.
 
Can you help me with uploading any recorded file to a (php) folder?
 
Here's the javascript code:
 
<script>
const video = document.querySelector('video')
const start = document.querySelector('.start')
const stop = document.querySelector('.stop')
const upload = document.querySelector('.upload')

const initRecorder = stream => {
const recorder = new MediaRecorder(stream)

  let blob

  video.srcObject = stream
  start.removeAttribute('disabled')

  video.addEventListener('loadedmetadata', () => {
    video.play()
  })

  recorder.addEventListener('dataavailable', ({ data }) => {
    video.srcObject = null
    video.src = URL.createObjectURL(data)

    // Create a blob from the data for upload
    blob = new Blob([data], { type: 'video/webm' })
  })

  start.addEventListener('click', () => {
    stop.removeAttribute('disabled')
    recorder.start()
  })

  stop.addEventListener('click', () => {
    upload.removeAttribute('disabled')
    recorder.stop()
  })

  // Upload the video blob as form data
  upload.addEventListener('click', () => {
    const body = new FormData()

    body.append('myvideo', blob)

    fetch('upload.php', { method: 'POST', body })
      .then(() => console.log('Success!'))
      .catch(console.error)

  })

  $myVideo = $_FILES['myvideo'];

  move_uploaded_file(
    $myVideo['tmp_name'],
    '../uploads/' . basename($myVideo['name'])
);

}

navigator
  .mediaDevices
  .getUserMedia({ video: true })
  .then(initRecorder)
  .catch(console.error)

  </script>

Any help will be welcomed

 

 

Well, for starters you can't mix Javascript and PHP. For two, you need to do more than simply move_uploaded_file() the upload: you have to make sure it's valid, make sure the form isn't being abused by anyone to upload anything, and deal with the name of the file rather than just reuse whatever name was assigned though the blob (and I'm not even sure one was).

 

The documentation explains file uploads, but it'll be better if you can find yourself a good tutorial on how to do them.

Thanks for your reply.

 

This web cam recorder script that I'm working with now performs uploads successfully, however, it is the same file name every time it uploads. I've added in some 'generate random file name' code (with ////// surrounding it below), but it doesn't tie in with the working code. Any help/guidance/remedy will be welcomed.

const video = document.querySelector('video')
const start = document.querySelector('.start')
const stop = document.querySelector('.stop')
const upload = document.querySelector('.upload')

const initRecorder = stream => {
const recorder = new MediaRecorder(stream)

  let blob

  video.srcObject = stream
  start.removeAttribute('disabled')

  video.addEventListener('loadedmetadata', () => {
    video.play()
  })

  recorder.addEventListener('dataavailable', ({ data }) => {
    video.srcObject = null
    video.src = URL.createObjectURL(data)

    // Create a blob from the data for upload
    blob = new Blob([data], { type: 'video/webm' })
  })

  start.addEventListener('click', () => {
    stop.removeAttribute('disabled')
    recorder.start()
  })

  stop.addEventListener('click', () => {
    upload.removeAttribute('disabled')
    recorder.stop()
  })


  // Upload the video blob as form data 
      upload.addEventListener('click', () => {
      uploadBlob(blob)

    })

  }


/////////////////////////////////////////////////////////////////////////////////////

   // this function is used to generate random file name
          function getFileName(fileExtension) {
              var d = new Date();
              var year = d.getUTCFullYear();
              var month = d.getUTCMonth();
              var date = d.getUTCDate();
              return 'RecordRTC-' + year + month + date + '-' + getRandomString() + '.' + fileExtension;
          }

          function getRandomString() {
              if (window.crypto && window.crypto.getRandomValues && navigator.userAgent.indexOf('Safari') === -1) {
                  var a = window.crypto.getRandomValues(new Uint32Array(3)),
                      token = '';
                  for (var i = 0, l = a.length; i < l; i++) {
                      token += a[i].toString(36);
                  }
                  return token;
              } else {
                  return (Math.random() * new Date().getTime()).toString(36).replace(/\./g, '');
              }
        }


//////////////////////////////////////////////////////////////////////////////////////

  function uploadBlob(blob) {
      var formData = new FormData();
      formData.append('video-blob', blob);
      formData.append('video-filename', 'myvideo.webm');
      $.ajax({
          url: "upload.php",
          type: "POST",
          data: formData,
          processData: false,
          contentType: false,

                    success: function(response) {
		                alert('Successfully uploaded.');
          },

          error: function(jqXHR, textStatus, errorMessage) {
              alert('Error:' + JSON.stringify(errorMessage));
          }
      });
  }


  navigator
    .mediaDevices
    .getUserMedia({ video: true })
    .then(initRecorder)
    .catch(console.error)

Don't bother using Javascript to create a random name. Just do it in PHP. Something like

sha1(microtime(true))
is probably sufficient, but really you should construct filenames that are guaranteed to be unique by including something particular, like an identifier from a database.
This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.