0

我有一个图像元素,我从中获取 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 中提交表单的位置。这种方法有什么问题还是有比这更好的方法?

感谢您对此的任何帮助,谢谢!

4

1 回答 1

1

不要使用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})
      )
    )
  }
}

您还可以做的是使用画布并避免另一个请求(但这会将所有图像转换为 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})
  })
}
于 2016-11-17T08:29:13.633 回答