最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Base64-encoding a Videofile in js - Stack Overflow

programmeradmin0浏览0评论

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.

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.

Share Improve this question asked Jul 6, 2016 at 13:51 njoyenjoye 3681 gold badge5 silver badges18 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 3

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

发布评论

评论列表(0)

  1. 暂无评论