Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

97
Views
javascript fetch an image and create base64

I'm using CloudFlare service workers and I want to fetch an image and then generate a base64 representation of it.

So something like this:

const res = await fetch('https://cdn.cnn.com/cnnnext/dam/assets/211010073527-tyson-fury-exlarge-169.jpg')
  const blob = await res.blob();
  
  console.log(blob)
  console.log(btoa(blob))

this of course doesn't work, any ideas how to get this resolved?

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

complete worker script with cloudflare using btao

addEventListener('fetch', event => {
  event.respondWith(handleRequest(event.request))
})

const imageUrl =
  'https://upload.wikimedia.org/wikipedia/commons/thumb/7/72/' +
  'Cat_playing_with_a_lizard.jpg/1200px-Cat_playing_with_a_lizard.jpg';

function base64Encode (buf) {
  let string = '';
  (new Uint8Array(buf)).forEach(
      (byte) => { string += String.fromCharCode(byte) }
    )
  return btoa(string)
}

function base64Decode (string) {
  string = atob(string);
  const
    length = string.length,
    buf = new ArrayBuffer(length),
    bufView = new Uint8Array(buf);
  for (var i = 0; i < length; i++) { bufView[i] = string.charCodeAt(i) }
  return buf
}

async function handleRequest(request) {
  const
    upstreamResponse = await fetch(imageUrl),
    text = base64Encode(await upstreamResponse.arrayBuffer()),
    bin = base64Decode(text);
  
  return new Response(bin, {status: 200, headers: {
      'Content-type': upstreamResponse.headers.get('Content-type')
    }})
}

can refer this discussion as well

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!