Skip to content

Instantly share code, notes, and snippets.

@EdixonAlberto
Created June 23, 2021 20:28
Show Gist options
  • Save EdixonAlberto/94dda6453a6ef59b24be8b0d2470e258 to your computer and use it in GitHub Desktop.
Save EdixonAlberto/94dda6453a6ef59b24be8b0d2470e258 to your computer and use it in GitHub Desktop.
helper toBase64
// helper.js
export async function toBase64(blob) {
return new Promise((resolve, reject) => {
const reader = new FileReader()
let fullStr = ''
const getPositionSymbol = symbol => {
return fullStr.search(symbol) + 1
}
reader.readAsDataURL(blob)
reader.onload = () => {
fullStr = reader.result
const content = fullStr.substring(getPositionSymbol(','))
const type = fullStr.substring(getPositionSymbol(':'), getPositionSymbol(';') - 1)
resolve({ content, type })
}
reader.onerror = error => reject(error)
})
}
// index.js
import { toBase64 } from './helper'
const { content, type } await toBase64(file) // the file comes from an input type file
const file = {
name: file.name,
content,
type
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment