javascript - 继续从服务器获取一个空数组,用于使用 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);
?>
解决方案
您能否尝试使用 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}`)
}
});
推荐阅读
- cmake - 如何在 CMAKE 中将标志传递给 nvcc 编译器
- php - 用mysql在php中进行分页
- javascript - Drupal 7:使用 drupal_add_js 时如何将 async 属性添加到外部 JS 脚本?
- node.js - 保存/创建时存在猫鼬检查值并通过响应发送
- java - 为什么我总是在 android 3.1.2 中出现 R 错误?
- ios - 在容器视图中设置委托
- ruby-on-rails - 使用 Rails/Bootstrap 布局将视图定位到侧边栏的右侧
- javascript - 禁用 Angularjs 模型弹出滚动条
- react-native - 样式化反应原生组件
- c - C中pid_t和int的区别