[英]How do I download an image and convert to base64 in javascript?
我可以在不下載的情況下將圖像發布到另一個頁面嗎? (轉換為 base64 並發布)
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)
我如何添加一些東西來下載這個圖像, http ://g1.gangsters.pl/php/sec_token.php?type=sa a 然后將它轉換為 base64 字符串?
如果我問對了你的問題
body
中發送 base64 您可以先等待(使用 Promise)FileReader 讀取 imageData。 .then
將 base64 傳遞給您的下一個(發布)函數:
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);
});
正如其他人所指出的,這應該在服務器端更好地處理。 來回發送圖像(+ 自 base64 編碼以來增加的重量的 1/4 - 以及允許 CORS 的服務器......)似乎是不必要的開銷。
所以sec_token.php
可以擴展到處理圖像轉發到ks_sa_100.php
(+ 必要的查詢參數,如co=61
或任何需要的)
# 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
資源:
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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.