[英]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.