WEB/JS

[Javascript] 내맘대로 파일 변환하기 (base64 to file / file to base64)

나나나나나나나ㅏ나난ㄴ나ㅏ나나 2022. 4. 25. 15:13
728x90

file to base64

function fileToBase64(file){
	const reader = new FileReader();
    reader.readAsDataURL(file)
    reader.onload = () => {
    	console.dir(reader.result)	// base64
    }
}

 

base64 to file

function dataURLtoFile(dataurl, filename) {

    var arr = dataurl.split(','),
        mime = arr[0].match(/:(.*?);/)[1],
        bstr = atob(arr[1]),
        n = bstr.length,
        u8arr = new Uint8Array(n);

    while(n--){
        u8arr[n] = bstr.charCodeAt(n);
    }



    return new File([u8arr], filename, {type:mime});
}
728x90