有什么方法可以在JavaScript中获取任何远程文件的base64编码字符串?

发布于 2025-01-21 03:18:23 字数 144 浏览 5 评论 0原文

我有一个图像网址:

url = "https://wallpaperaccess.com/full/3678503.png";

有没有办法在 JavaScript 中获取该远程文件的 Base64 编码字符串?

I have an image url:

url = "https://wallpaperaccess.com/full/3678503.png";

Is there any way to get base64 encoded string of that remote file in javascript?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

薄荷→糖丶微凉 2025-01-28 03:18:23

我在这个代码上找到了实现这一目标的代码。唯一的问题是您会遇到CORS问题。如果您是托管图像的页面的所有者,则可以配置以避免CORS。

const toDataURL = url => fetch(url)
  .then(response => response.blob())
  .then(blob => new Promise((resolve, reject) => {
    const reader = new FileReader()
    reader.onloadend = () => resolve(reader.result)
    reader.onerror = reject
    reader.readAsDataURL(blob)
  }))


toDataURL('https://wallpaperaccess.com/full/3678503.png')
  .then(dataUrl => {
    console.log('RESULT:', dataUrl)
  })

在这里找到来源的链接: https://stackoverflow.com/a/a/20285053/14807111

I found on SO this codesnipet to achieve this. The only problem would be that you will run into CORS Problem. If you are the owner of the page which hosted the image you can configure up to avoid CORS.

const toDataURL = url => fetch(url)
  .then(response => response.blob())
  .then(blob => new Promise((resolve, reject) => {
    const reader = new FileReader()
    reader.onloadend = () => resolve(reader.result)
    reader.onerror = reject
    reader.readAsDataURL(blob)
  }))


toDataURL('https://wallpaperaccess.com/full/3678503.png')
  .then(dataUrl => {
    console.log('RESULT:', dataUrl)
  })

And here the Link where i found the source: https://stackoverflow.com/a/20285053/14807111

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文