简体   繁体   中英

Javascript send video blob to PHP - how to also send mimetype?

I'm generating a blob in JavaScript via a recorded video stream ( MediaRecorder ).

The resultant file ends up as a .webm, as confirmed by ffmpeg. So far, so good. Here's what I'm doing.

//promises container
let dfds = [];

//promise 1 - get blob file content
dfds.push(new Promise(resolve => {
    var xhr = new XMLHttpRequest();
    xhr.open('GET', file_url, true);
    xhr.responseType = 'blob';
    xhr.onload = function(e) {
        if (this.status == 200) resolve(this.response);
    };
    xhr.send();
}));

//(other non-pertinent promises omitted here)

//when ready, build and send request
Promise.all(dfds).then(resolution_data => {
    let req = new XMLHttpRequest(), fd = new FormData();
    fd.append('title', title);
    fd.append('file', resolution_data[0]); //<-- the blob
    req.open('POST',  'my-script.php');
    req.send(fd);
});

This works perfectly. However, on the PHP side, when I run print_r($_FILES) , the mime type is ending up as text/plain. I'd like to submit to PHP the mime type, so I can check this before allowing the file through (I'm aware mimetype is not always reliable, but it's just another check of several I'm doing.)

I added this to the AJAX request:

req.setRequestHeader('Content-Type', 'video/webm');

However with this added, the PHP script reports that $_FILES is completely empty.

How can I submit the mime type along with the file?

The formData.append() as a 'filename' field. See:

https://developer.mozilla.org/en-US/docs/Web/API/FormData/append

What would happen if you gave it a name like 'myMovie.webm'? It's worth a try, I think. So:

fd.append('file', resolution_data[0]); 

would become:

fd.append('file', resolution_data[0], 'myMovie.webm'); 

I haven't tested this at all, it's just a suggestion.

Since you haven't reacted yet, I read a bit more. I also found this:

https://developer.mozilla.org/en-US/docs/Web/API/FormData/Using_FormData_Objects

in it they use this code:

var content = '<a id="a"><b id="b">hey!</b></a>'; 
var blob = new Blob([content], { type: "text/xml"});
formData.append("webmasterfile", blob);

Note the mime type! That looks very promising!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM