因此,我有一个网站可以记录来自用户网络摄像头的视频流,并使用getUserMedia()
将其转换为blob。我现在想将此Blob发送到服务器,以便可以保存和处理视频。我有麻烦通过ajax发送blob文件,我尝试使用formData + XMLHttpRequest()方法以及纯ajax。用户可以录制视频并立即将视频发送到我的服务器,这对我的应用程序来说至关重要。
任何帮助将不胜感激。
是HTML:
<div class="demo">
<video id="preview" autoplay width="400" height="300"></video>
<video id="recording" width="400" height="300" style="display:none;" controls></video>
<div class="progress">
<div class="progress-bar"></div>
<span>01:00</span>
</div>
<button class="record">Record</button>
<button class="upload">Upload</button>
</div>
相关JS功能:
function captureVideo () {
const preview = document.querySelector('video#preview');
const recording = document.querySelector('video#recording');
navigator.mediaDevices.getUserMedia({video: true}).then((stream) => {
preview.srcObject = stream;
preview.captureStream = preview.captureStream || preview.mozCaptureStream;
return new Promise(resolve => preview.onplaying = resolve);
}).then(() => {
let recorder = new MediaRecorder(preview.captureStream());
let data = [];
recorder.ondataavailable = event => data.push(event.data);
recorder.start();
log(recorder.state + " for " + (60000/1000) + " seconds...");
let stopped = new Promise((resolve, reject) => {
recorder.onstop = resolve;
recorder.onerror = event => reject(event.name);
});
$('button.stop').click(function () {
recorder.stop();
});
return Promise.all([ stopped ]).then(() => data);
}).then ((recordedChunks) => {
let recordedBlob = new Blob(recordedChunks, {
type: "video/webm"
});
recording.src = URL.createObjectURL(recordedBlob);
$('#preview').hide();
$('#recording').show();
log("Successfully recorded " + recordedBlob.size + " bytes of " +
recordedBlob.type + " media.");
$('button.upload').click(function() {
sendVideoToAPI(recordedBlob);
});
}).catch(log);
}
function sendVideoToAPI (blob) {
let fd = new FormData();
let file = new File([blob], 'recording');
fd.append('data', file);
console.log(fd); // test to see if appending form data would work, it didn't this is completely empty.
let form = new FormData();
let request = new XMLHttpRequest();
form.append("file",file);
request.open("POST", "/demo/upload", true);
request.send(form); // hits the route but doesn't send the file
console.log(request.response) // returns nothing
// I have also tried this method which hits the route and gets a response however the file is not present in the request when it hits the server.
// $.ajax({
// url: Routing.generate('upload'),
// data: file,
// contentType: false,
// processData: false,
// error: function (res) {
// console.log(res);
// },
// success: function(res) {
// console.log(res);
// }
// });
}
答案 0 :(得分:1)
您正在发送ajax请求,在send()命令之后您将不会立即获得响应。您可以使用request onload事件
访问响应值{{1}}