Turning audio and video into Base64

2

I would like to know if it would be possible to transform videos and audios in Base64, I already asked a question related to transform image in Base64 and you helped me, but now I need to do the same for audio and video, I had thought it would be the same process of the image but it is not working.

This is the link from my previous question and the solution I found also posted here

The application I'm developing is mobile, I need to convert it to send to the server and then the server will unconvert and work with the file.

This is the code of my server side that receives the Base64 file as the parameter and the name to convert and save to a directory:

public void ProcessRequest(HttpContext context)
    {
        context.Response.ContentType = "text/plain";

        System.IO.Stream body = context.Request.InputStream;
        System.Text.Encoding encoding = context.Request.ContentEncoding;
        System.IO.StreamReader reader = new System.IO.StreamReader(body, encoding);

        //obtem postDATA
        string postData = reader.ReadToEnd();
        NameValueCollection param = HttpUtility.ParseQueryString(postData);


        //params
        // filename = nome do arquivo
        // d = conteudo binario codificado em base64
        // UserId = id do usuario
        // Date = data no formato json

        //salva arquivo

        if (param["filename"] != null && param["d"] != null)
        {
            Directory.CreateDirectory("C:\Uploads");
            string strSaveLocation = ("C:\Uploads") + "\" + param["filename"];
            FileStream fs1 = new FileStream(strSaveLocation, FileMode.OpenOrCreate, FileAccess.Write);
            BinaryWriter bw = new BinaryWriter(fs1);

            try
            {
                //tenta converter vindo em base64
                byte[] decbuff = Convert.FromBase64String(param["d"]);
                bw.Write(decbuff);
            }
            catch (Exception e)
            {
                //failover - salva sem conversao
                bw.Write(param["d"]);
            }

            bw.Close();
            fs1.Close();

            //responde OK
            context.Response.Write("{\"StatusRetorno\":0,\"MensagemRetorno\":\"Operacao_Realizada\",\"idSync\":}");
        }
        else
        {

            //responde erro
            context.Response.Write("{\"StatusRetorno\":1,\"MensagemRetorno\":\"could not save file\"}");
        }

        body.Close();
        reader.Close();
    }
    
asked by anonymous 24.08.2015 / 15:19

3 answers

1

I would like to post an alternative, in this case converting a Blob to base64.

var uploadFile = document.getElementById("uploadFile");
var btBase64 = document.getElementById("btBase64");
var taBase64 = document.getElementById("taBase64");
var imgBase64 = document.getElementById("imgBase64");

btBase64.addEventListener("click", function () {
  if (uploadFile.files.length > 0) {
    var file = uploadFile.files[0];
    
    blobToBase64(uploadFile.files[0], function (base64) {
      taBase64.innerHTML = base64;
      imgBase64.src = "data:" + file.type + ";base64," + base64;
    });    
    
    //if (file.type.indexOf("image") === 0) {
    //  imgBase64.src = URL.createObjectURL(uploadFile.files[0]);
    //}
  }
});

var blobToBase64 = function(blob, callback) {
  var fileReader = new FileReader();
  fileReader.onload = function(e) { 
    var binary = [].slice.apply(new Uint8Array(fileReader.result));     
    var str = binary.map(function (charCode) {
      return String.fromCharCode(charCode);
    }).join("");  
    callback(btoa(str));
  };
  fileReader.readAsArrayBuffer(blob);
}
textarea {
  width: 100%;
  height: 200px;
}
<div>
  <input id="uploadFile" type="file" />
</div>
<div>
  <input id="btBase64" type="button" value="Para Base64" />
</div>
<div>
  <textarea id="taBase64" type="button" value="Para Base64" >
  </textarea>
</div>
<div>
  <img id="imgBase64" />
</div>

To get a local file, you can make an ajax request:

var xmlHttp = new XMLHttpRequest();
xmlHttp.open('GET', fileName, true);
xmlHttp.responseType = "blob";
xmlHttp.onreadystatechange = function() {
  if (xmlHttp.readyState == 4 && (xmlHttp.status == 200 || xmlHttp.status == 0)) {        
    var base64 = blobToBase64(xmlHttp.response)
  }
}
xmlHttp.send();
    
24.08.2015 / 16:32
0

For video you can use:

    videodata = Base64.encodeToString(objByteArrayOS.toByteArray(), Base64.DEFAULT);

For audio you can use:

    File file = new File(Environment.getExternalStorageDirectory() + "/hello-4.wav");
    byte[] bytes = FileUtils.readFileToByteArray(file);

    String encoded = Base64.encodeToString(bytes, 0);                                       
    Utilities.log("~~~~~~~~ Encoded: ", encoded);

    byte[] decoded = Base64.decode(encoded, 0);
    Utilities.log("~~~~~~~~ Decoded: ", Arrays.toString(decoded));

    try
    {
    File file2 = new File(Environment.getExternalStorageDirectory() + "/hello-5.wav");
    FileOutputStream os = new FileOutputStream(file2, true);
    os.write(decoded);
    os.close();
    }
    catch (Exception e)
    {
    e.printStackTrace();
    }
    
24.08.2015 / 15:35
-1

I have a very simple python code that I have developed, which takes a .webm video, converts to base64 and saves it to the mysql database. The first inclusion in the table I made the hand. then the rest the program does (I was too lazy to think).

import base64
#!/usr/bin/env python
from datetime import datetime
import os
import sys
import string
import MySQLdb
from gi.repository import Gtk
import gtk
from time import time, sleep
from sched import scheduler
import Tkinter as tk
import tkFileDialog as filedialog

db = MySQLdb.connect(host="localhost", user="root", passwd="", db="imagens")
cursor = db.cursor()


cursor.execute('SELECT codigo FROM CODIFICADAS ORDER BY codigo DESC LIMIT 1')
resultado = cursor.fetchall()
for dados in resultado:
    numero = dados[0]
    numerar = int(numero)
    if numerar >= 1:
        numerar = numerar +1
        numerar = int(numerar)


    nome = "arquivo %s" %(numerar)
root = tk.Tk()
root.withdraw()
imagem = filedialog.askopenfilename()
with open(imagem, "rb") as f:
           data = f.read()
           decode = data.encode("base64")
           decode = str(decode)
           gravar = open('ARQUIVO.txt' ,'w')
           gravar.write(decode)
cursor.execute("INSERT INTO CODIFICADAS (nome, decode) VALUES( '" + nome + "',  '" + decode + "')")
db.commit()
    
23.05.2017 / 20:08