在javascript中将十六进制字符串转换为base64
问题描述:
现在我有一个文件的MD5十六进制摘要字符串,我想将其转换为base64,以便在上传时使用Content-MD5 HTTP标头。
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.
任何帮助都将不胜感激
答
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);
请参阅此处了解btoa文档: https://developer.mozilla.org/en-US/docs/Web/API/WindowBase64/btoa
See here for btoa docs: https://developer.mozilla.org/en-US/docs/Web/API/WindowBase64/btoa
也适用于polyfill: https://stackoverflow.com/a/23190164/275501
Also for polyfill: https://stackoverflow.com/a/23190164/275501