【问题标题】:upload image file converted from html to s3上传从html转换为s3的图像文件
【发布时间】:2021-03-24 05:24:36
【问题描述】:

我有一段 HTML,我使用 html-to-image 将其转换为图像,现在我需要将该图像文件上传到 s3。

转换后得到的是base 64 url​​。我在远程后端设置了 s3,我将文件发送到 api 路由并将其上传到 s3 并返回文件的 s3 url。

我怎样才能把这个base url转换成图片obj并发送到api?

html转img功能:

htmlToImage.toPng(document.getElementById('my-node'))
  .then(function (dataUrl) {
    // do stuff with url
});

【问题讨论】:

标签: reactjs amazon-s3 blob


【解决方案1】:

有一个非常简单的通用函数将图像数据 url 转换为文件对象,定义如下:

function dataURLtoFile(dataurl, filename) {
  var arr = dataurl.split(','), mime = arr[0].match(/:(.*?);/)[1],
    bstr = atob(arr[1]), n = bstr.length, u8arr = new Uint8Array(n);
  while(n--){
    u8arr[n] = bstr.charCodeAt(n);
  }
  return new File([u8arr], filename, { type:mime });
}

// Usage in your case

htmlToImage.toPng(document.getElementById('my-node'))
  .then(function (dataUrl) {
    const yourFile = dataURLtoFile(dataUrl, 'yourImageName');   
  });

【讨论】:

  • 像魅力一样工作!非常感谢。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-12-19
  • 2012-12-26
  • 2011-08-31
  • 2012-06-29
  • 2018-01-16
相关资源
最近更新 更多