将Blob字符串URL转换为Blob,然后转换为base64

Convert Blob string URL to Blob then to base64

本文关键字:转换 Blob 然后 base64 字符串 URL      更新时间:2023-09-26

我有一个图像元素,我从那里得到blob字符串URL,我正试图将其转换为blob,然后转换为base64字符串。这样我就可以发送base64字符串(这是存储在#originalImage)到服务器端。

JS

            onFinished: function (event, currentIndex) {
            var form = $(this);
            if ($('#image').attr('src').length) {
                var selectedFile = $('#image').attr('src');
                var blob;
                var reader = new window.FileReader();
                var xhr = new XMLHttpRequest();
                xhr.onreadystatechange = function () {
                    if (this.readyState == 4 && this.status == 200) {
                        blob = this.response;
                        console.log(this.response, typeof this.response);
                        if (blob != undefined) {
                            reader.readAsDataURL(blob);
                        }
                    }
                }
                xhr.open('GET', selectedFile);
                xhr.responseType = 'blob';
                xhr.send();

            }
            reader.onloadend = function () {
                base64data = reader.result;
                console.log(base64data);
                if (base64data != undefined) {
                    $("#originalImage").val(base64data);
                    form.submit();
                }
            }
        }
控制器

        [HttpPost]
        public ActionResult Action(Model blah, string croppedImage, string originalImage){
              // Code here...
         }

它按预期工作,但我唯一关心的是,我在哪里提交的形式是在reader.onloadend。这种方法有什么问题吗?或者有比这更好的方法吗?

我感谢任何帮助,谢谢!

不使用base64,发送二进制到服务器,节省时间、进程、内存和带宽

onFinished(event, currentIndex) {
  let src = $('#image').attr('src')
  if (src.length) {
    fetch(src)
    .then(res => 
      res.ok && res.blob().then(blob =>
        fetch(uploadUrl, {method: 'post', body: blob})
      )
    )
  }
}

你也可以使用canvas并避免另一个请求(但这会将所有图像转换为png)

onFinished(event, currentIndex) {
  let img = $('#image')[0]
  if (!img.src) return
  let canvas = document.createElement('canvas')
  let ctx = canvas.getContext('2d')
  canvas.width = img.width
  canvas.height = img.height
  ctx.drawImage(img, 0, 0)
  canvas.toBlob(blob => {
    fetch(uploadUrl, {method: 'post', body: blob})
  })
}