Created
June 23, 2021 20:28
-
-
Save EdixonAlberto/94dda6453a6ef59b24be8b0d2470e258 to your computer and use it in GitHub Desktop.
helper toBase64
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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