Converting a hexadecimal string to base64 in javascript [duplicate]

心不动则不痛 提交于 2020-01-03 00:39:33

问题


Now I have a string of a MD5 hex digest for a file, and I want to convert it to base64 in order to use the Content-MD5 HTTP header when uploading it.

Any help would be appreciated


回答1:


var hexArray = myHexString
    .replace(/\r|\n/g, "")
    .replace(/([\da-fA-F]{2}) ?/g, "0x$1 ")
    .replace(/ +$/, "")
    .split(" ");
var byteString = String.fromCharCode.apply(null, hexArray);
var base64string = window.btoa(byteString);

See here for btoa docs: https://developer.mozilla.org/en-US/docs/Web/API/WindowBase64/btoa

Also for polyfill: https://stackoverflow.com/a/23190164/275501




回答2:


Modern browsers has built in functions for this: https://developer.mozilla.org/en-US/docs/Web/API/WindowBase64/Base64_encoding_and_decoding

For older browsers you'll need a library such as https://github.com/beatgammit/base64-js



来源:https://stackoverflow.com/questions/30613897/converting-a-hexadecimal-string-to-base64-in-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!