简体   繁体   中英

How do I download an image and convert to base64 in javascript?

Can I post an Image to another page without downloading it? (convert to base64 and post)

function run(){
  const url = 'http://g1.gangsters.pl/php/ks_sa_100.php?co=61';
  const body = new FormData()
  body.append('blokada', true)
  body.append('y', Math.floor(Math.random() * (100 - 100 + 1)) + 100)

  fetch(url, { method: 'POST', body })
}

setInterval(() => {
  console.log('Robbing....')
  run()
}, 1700)

How do I add something to download this image, http://g1.gangsters.pl/php/sec_token.php?type=sa a then convert it to a base64 string?

If I got your question right

  • first get an image into base64,
  • send afterwards that base64 within a body of a POST request

You could first wait (using Promise) that a FileReader reads the imageData. .then pass the base64 to your next (post) function:

const toDataURL = (url) => fetch(url)
  .then(res => res.blob())
  .then(blob => new Promise((res, err) => {
    const FR = new FileReader();
    FR.onloadend = () => res(FR.result);
    FR.readAsDataURL(blob);
    FR.onerror = err;
  }));

const toSecToken = toDataURL('http://g1.gangsters.pl/php/sec_token.php?type=sa')
  .then(base64 => {
    const body = new FormData();
    body.append('base64', base64);
    body.append('blokada', true);
    body.append('y', Math.floor(Math.random() * (100 - 100 + 1)) + 100);
    return fetch('http://g1.gangsters.pl/php/ks_sa_100.php?co=61', { method:'POST', body });
  });

toSecToken.then(res => {
    console.log(res);
});

As noted by others, this should be better handled on the server side. Sending an image back and forth (+ the 1/4 of added weight since the base64 encoding - and a server that allows CORS...) seems like an unnecessary overhead.
So the sec_token.php could be extended to handle the image forwarding to ks_sa_100.php (+ the necessary query params like co=61 or whatever is needed)

# ks_sa_100.php?co=61

$img = file_get_contents('http://g1.gangsters.pl/php/sec_token.php?type=sa');  
$base64 = base64_encode($img); // if you really need that base64 data string

Resources:

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Using_promises
https://developer.mozilla.org/en-US/docs/Web/API/FileReader
https://developer.mozilla.org/en-US/docs/Web/API/FileReader/readAsDataURL
https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM