Help modify my function to generate random file name

This web cam recorder script that I’m working with performs 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 'blob' + 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)

Why not just use Date.now() to get a different value every time, which is the number of milliseconds that has elapsed since 1/1/1970 ? It’s much simpler, and works well.

function getFileName(fileExtension) {
    var nowMilli = Date.now();
    return "blob" + nowMilli + "." + fileExtension;
}
2 Likes

Thanks for your reply.

I tried it without success(below). I need help tying it into my existing script. Any help will be appreciated.


.............................


  // Upload the video blob as form data ............................

      upload.addEventListener('click', () => {
      uploadBlob(blob)

    })

  }

function getFileName(fileExtension) {
    var nowMilli = Date.now();
    return "blob" + nowMilli + "." + fileExtension;
}


  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)

    </script>

Do you see where “myvideo.webm” is mentioned? Replace that with getFileName("webm")

The .append() method takes a file name as an (optional) third parameter… but you can actually just name that file as you like on the backend anyway (namely the $destination parameter of the move_uploaded_file() function).

Thank you again

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.