Turn Audio & Video into Base64

Asked

Viewed 1,384 times

2

I wonder if it would be possible to turn videos and audios into Base64, I already posted a question related to transforming image into 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 image process but it’s not working.

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

The application I’m developing is mobile, I need to convert to send to the server and then the server disconnect and work with the file.

This is the code of my server side that receives as parameter the file in Base64 and the name to convert and save in 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();
    }

3 answers

1

would like to post an alternative, in case converting a Blob into 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 grab 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();
  • Thanks, however I have a doubt, the return of the converted file comes by the variable base64, if the file is an image or video and I want to take the value in base64 and display below the textarea(to test whether the conversion is actually working correctly) how should I do? I tried sending so document.getElementById("imgBase64").innerHTML = '<img src="data:image/png;base64,' + base64 + '">'; but it didn’t work.

  • Vinicius, once you have a blob, you can create a url for the blob, I will update the example.

  • Vinicius, I updated the example to mount the image in the source itself, however I left an excerpt of commented code, where we create a URL for the file in memory (which is what I recommend).

  • it worked, however with my previous code I sent the file in Base64 to an ajax and it sent to my server side that decoded and saved the file in a directory, now it is not able to decode, it sends the file to my directory but the image for example opens all black, I will post the code of my server side if you can help me. (Thank you for your attention so far)

  • Vinicius, there was a mistake in blobToBase64, try again now, remember that you also have to pass the type of the object serialized in AJAX.

  • is working now, the server side is decoding, I will pass the image as soon as the user takes the photo, he will not be able to take from the gallery, I have as return of the photo taking function the path+name+extension (file:/Storage/../photo.jpg), has how I pass this return to the encoding function and she perform the encoding?

  • tried to use the camera.getPicture, it even returns you the image in the format you need.

  • would it be possible to chat? It’s easier for me to explain my situation

  • firewall does not allow.

  • OK @Tobymosque, what happens is that the user can send multiple media (photo, audio, video) until the moment my app is taking these files and saving all their paths in a div, which then turn into an array and send to my ajax upload data, I have a function that works for images, what I needed to know is if I would have how to adapt the function that sent me to receive the media path transform it and send to my ajax. (The camera.getPicture does not provide why not send the moment I take the photo I have to send later, when the user wants to register)

  • @Viniciusvaz, in this case you can use a Storage, create a short time table CREATE TABLE IF NOT EXISTS FILES (file_uuid unique, name, type, base64) to store the files, so when the user needs to upload it would only have to read the Storage and send by AJAX.

Show 7 more comments

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();
    }
  • Thanks, I only had a doubt, when I will convert an image I pass by parameter the path that this, what are the parameters that I must pass when calling these functions?

  • Apparently the doubt of AP is to make this conversion with Javascript, not Java.

-1

I have a very simple python code that I developed, which takes a video . webm, converts to Base64 and saves it in the mysql database. The first inclusion in the table I made the hand. after the rest the program makes(I was 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()

Browser other questions tagged

You are not signed in. Login or sign up in order to post.