我有一个图像元素,我从中获取 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();
}
}
}
Controller
[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})
})
}
关于javascript - 将 Blob 字符串 URL 转换为 Blob,然后转换为 base64,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40606720/