首页 > 解决方案 > 继续从服务器获取一个空数组,用于使用 blob/文件对象发送的 FormData

问题描述

我目前对以下代码有疑问。即使我发送带有创建并附加到所述 FormData 的 .mp4 blob/文件的 FormData ,我仍然从 upload.php返回一个空数组。只是不清楚为什么它是空的,因为我什至可以 console.log 我创建的 FormData 对象并清楚地看到添加了 blob/file 对象。所以真的不知道为什么服务器没有得到它。我已经四处寻找解决方案,但无济于事。

给予的任何帮助将不胜感激。提前致谢

<!--INDEX.HTML-->
<!DOCTYPE html>
<html>
  <head>
    <title>Media Recorder in Javascript</title>
    <link rel="stylesheet" href="./main.css" />
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.5.1/jquery.min.js" integrity="sha512-bLT0Qm9VnAYZDflyKcBaQ2gg0hSYNQrJ8RilYldYQ1FxQYoCLtUjuuRuZo+fjqhx/qtq/1itJ0C2ejDxltZVFg==" crossorigin="anonymous"></script>
  </head>
  <body>
    <div id="container">
      <video id="gum" playsinline autoplay muted></video>
      <video id="recorded" playsinline loop></video>

      <div>
        <button id="start">Start camera</button>
        <button id="record" disabled>Record</button>
        <button id="play" disabled>Play</button>
        <button id="download" disabled>Download</button>
      </div>

      <div>
        <h4>Media Stream Constraints options</h4>
        <p>
          Echo cancellation: <input type="checkbox" id="echoCancellation" />
        </p>
      </div>
      
      <div>
        <span id="errorMsg"></span>
      </div>
    </div>
  </body>
  <script src="./script.js"></script>

</html>





//SCRIPT.JS
'use strict';

/* globals MediaRecorder */

let mediaRecorder;
let recordedBlobs;

const errorMsgElement = document.querySelector('span#errorMsg');
const recordedVideo = document.querySelector('video#recorded');
const recordButton = document.querySelector('button#record');
const playButton = document.querySelector('button#play');
const downloadButton = document.querySelector('button#download');


recordButton.addEventListener('click', () => {
  if (recordButton.textContent === 'Record') {
    startRecording();
  } else {
    stopRecording();
    recordButton.textContent = 'Record';
    playButton.disabled = false;
    downloadButton.disabled = false;
  }
});


playButton.addEventListener('click', () => {
  const superBuffer = new Blob(recordedBlobs, {type: 'video/webm'});
  recordedVideo.src = null;
  recordedVideo.srcObject = null;
  recordedVideo.src = window.URL.createObjectURL(superBuffer);
  recordedVideo.controls = true;
  recordedVideo.play();
});


downloadButton.addEventListener('click', () => {
    const blob = new Blob(recordedBlobs, {type: 'video/mp4'});

    const fdata = new FormData()

    var fileOfBlob = new File([blob], 'aFileName.mp4');
    fdata.append("upload", fileOfBlob);

    for (var key of fdata.entries()) {
        console.log(key[0] + ', ' + key[1]);
    }
      $.ajax({
          url: "upload.php",
          enctype: 'multipart/form-data',
          type: 'POST',
          blob: fdata,
          contentType: false,
          processData: false,
          success: function(data) {
              // Sent to Server
              console.log(`${data}`)
          }
      });


});


function handleDataAvailable(event) {
  console.log('handleDataAvailable', event);
  if (event.data && event.data.size > 0) {
    recordedBlobs.push(event.data);
  }
}

function startRecording() {
  recordedBlobs = [];
  let options = {mimeType: 'video/webm;codecs=vp9,opus'};
  try {
    mediaRecorder = new MediaRecorder(window.stream, options);
  } catch (e) {
    console.error('Exception while creating MediaRecorder:', e);
    errorMsgElement.innerHTML = `Exception while creating MediaRecorder: ${JSON.stringify(e)}`;
    return;
  }

  console.log('Created MediaRecorder', mediaRecorder, 'with options', options);
  recordButton.textContent = 'Stop Recording';
  playButton.disabled = true;
  downloadButton.disabled = true;
  mediaRecorder.onstop = (event) => {
    console.log('Recorder stopped: ', event);
    console.log('Recorded Blobs: ', recordedBlobs);
  };
  mediaRecorder.ondataavailable = handleDataAvailable;
  mediaRecorder.start();
  console.log('MediaRecorder started', mediaRecorder);
}

function stopRecording() {
  mediaRecorder.stop();
}

function handleSuccess(stream) {
  recordButton.disabled = false;
  console.log('getUserMedia() got stream:', stream);
  window.stream = stream;

  const gumVideo = document.querySelector('video#gum');
  gumVideo.srcObject = stream;
}

async function init(constraints) {
  try {
    const stream = await navigator.mediaDevices.getUserMedia(constraints);
    handleSuccess(stream);
  } catch (e) {
    console.error('navigator.getUserMedia error:', e);
    errorMsgElement.innerHTML = `navigator.getUserMedia error:${e.toString()}`;
  }
}

document.querySelector('button#start').addEventListener('click', async () => {
  const hasEchoCancellation = document.querySelector('#echoCancellation').checked;
  const constraints = {
    audio: {
      echoCancellation: {exact: hasEchoCancellation}
    },
    //video: false   
    video : {width: 1280, height: 720}
  };
  console.log('Using media constraints:', constraints);
  await init(constraints);
});



//UPLOAD.PHP

<?php
var_dump($_POST);

?>

标签: javascriptblobform-dataweb-mediarecorder

解决方案


您能否尝试使用 ajax 响应类型:

xhrFields: { 
    responseType: "blob" 
},

blob并将密钥更改为name密钥。例如:

$.ajax({
          url: "upload.php",
          enctype: 'multipart/form-data',
          type: 'POST',
          xhrFields: { 
              responseType: "blob" 
          },
          data: fdata,
          contentType: false,
          processData: false,
          success: function(data) {
              // Sent to Server
              console.log(`${data}`)
          }
      });

推荐阅读