Base64-encoding a Videofile in js

一个人想着一个人 提交于 2021-02-08 06:47:57

问题


So i've got a video file and the path to it (e.g. /outerfolder/innerfolder/video.mp4). I now want to encode this video with Base64 in JS so that I am able to store it in a database. If you could help me with the encoding of the video file, I would be very thankful. Thanks in advance.


回答1:


You could encode the file with the following function to convert your file to an ArrayBuffer:

[update]

//<input type=file id="encondeMP4">
var encodeMP4 = document.getElementById('encondeMP4');

You now add an event listener to when file input changes

window.onload = function () {
    //add eventlisteners

    encodeMP4.addEventListener('change', someFunction);
}

you need a function to handle the call from the eventlistener

function someFunction(){
    encode(arrayBufferToString)
}

function encode(callback){
    var file = encodeMP4.files[0];
    var reader = new FileReader();
    reader.onload = function(e){
        var contents = e.target.result;
        var contentBuffer = arrayBufferToString(contents);
        var array = callback(contentBuffer);
    }
    reader.readAsArrayBuffer(file);
}

in var array you now have the MP4 enconded in binary, in the previous function is an internal variable so you'll need to adapt this code to your needs. Maybe a global container called YourEncodedMP4 = array

function arrayBufferToString(buffer) {
    var binary = '';
    var bytes = new Uint8Array( buffer );
    var len = bytes.byteLength;
    for (var i = 0; i < len; i++) {
        binary += String.fromCharCode( bytes[ i ] );
    }
    return binary;
}

you now are ready to call this function to convert the MP4 enconded String to a Base64 one.

Is up to you where the contents of var array would be stored, but remembered this call is asynchronous.

Now you could use this function using the container "YourEncodedMP4"

function stringToArrayBuffer(YourEncodedMP4) {
    var arrBuff = new ArrayBuffer(YourEncodedMP4.length);
    var writer = new Uint8Array(arrBuff);
    for(var i = 0, len = YourEncodedMP4.length; i < len; i++){
        writer[i] = YourEncodedMP4.charCodeAt(i);
    }

    return writer;
}

you now have a function that returns a Byte Array, than you could use

var base64String = btoa(String.fromCharCode.apply(null, new Uint8Array(stringToArrayBuffer(YourEncodedMP4))));

you'll end up with a StringBase64



来源:https://stackoverflow.com/questions/38225736/base64-encoding-a-videofile-in-js

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!