zeke1
zeke1

Reputation: 31

How to convert a video into base64 using expo(Filesystem)

Im trying to send a video to cloudinary and ive seem some similar questions but none answer mine. How do i use "Filesystem.readAsStringAsync" to convert my video so i can send it to cloudinary. Heres some of my code .

    let pickerResult = await ImagePicker.launchImageLibraryAsync({
    allowsEditing: true,
    aspect: [4, 3], 
    base64: true, 
    mediaTypes: ImagePicker.MediaTypeOptions.Videos, 
    });

    if (pickerResult.cancelled === true) { 
    return; 
    } 

    const base64Img 
    =`data:video/mp4;base64,${FileSystem.readAsStringAsync(pickerResult.uri{encoding: 
    'base64'})}`;

    let data = {
    "file": base64Img, 
    "upload_preset": "******",
     } 

     const r = await fetch(CLOUDINARY_URL, { 
     body: data,
     method: 'POST',
     }) 
     const datal = await r.json()
     setVideo(datal.secure_url); };

I know for a fact this is not the right way to use it , because it just keeps returning a empty string or null, please tell me how i can fix this if you need more info just comment

Upvotes: 0

Views: 1966

Answers (1)

Kartikey
Kartikey

Reputation: 4992

The way to read the file for base64 string is wrong.

Do it in the following way.

let pickerResult = await ImagePicker.launchImageLibraryAsync({
  allowsEditing: true,
  aspect: [4, 3],
  base64: true,
  mediaTypes: ImagePicker.MediaTypeOptions.Videos,
});

if (pickerResult.cancelled === true) {
  return;
}

const fsRead = await FileSystem.readAsStringAsync(pickerResult.uri, {
  encoding: "base64",
});

const base64Img = `data:video/mp4;base64,${fsRead}`;
// This looks like data:video/mp4;base64,AAAAIGZ0eXBpc29tAAACAGlzb21pc28yYXZjMW1wNDEAADGUbW9vdgAAAGxtdmhkAAAAAAAAAAAAAA

let data = {
  file: base64Img,
  upload_preset: "******",
};

const r = await fetch(CLOUDINARY_URL, {
  body: data,
  method: "POST",
});

const datal = await r.json();
setVideo(datal.secure_url);

Upvotes: 2

Related Questions