Home > Web Front-end > JS Tutorial > How to Efficiently Convert an ArrayBuffer to a Base64 String for Multipart Post Requests?

How to Efficiently Convert an ArrayBuffer to a Base64 String for Multipart Post Requests?

Susan Sarandon
Release: 2024-12-25 05:45:17
Original
989 people have browsed it

How to Efficiently Convert an ArrayBuffer to a Base64 String for Multipart Post Requests?

Native Conversion of ArrayBuffer to Base64-Encoded String for Multipart Post

Question: How can I convert an ArrayBuffer to a base64-encoded string for use in multipart posts, with an emphasis on native efficiency?

Answer: Implement the following function:

function _arrayBufferToBase64(buffer) {
  var binary = '';
  var bytes = new Uint8Array(buffer);
  var len = bytes.byteLength;
  for (var i = 0; i < len; i++) {
    binary += String.fromCharCode(bytes[i]);
  }
  return window.btoa(binary);
}
Copy after login

However, note that non-native implementations tend to offer superior speed. For such a use case, consider the following alternative: https://gist.github.com/958841

Benchmarks:

  • http://jsperf.com/encoding-xhr-image-data/6
  • https://jsben.ch/wnaZC

The above is the detailed content of How to Efficiently Convert an ArrayBuffer to a Base64 String for Multipart Post Requests?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template