[英]Converting data:image base64 to blob in this code
我想将 URL 从 data:image base64 更改为 blob。 这是生成 base64 url 的原始代码:
<script>
$(window).load(function(){
function readURL() {
var $input = $(this);
var $newinput = $(this).parent().parent().parent().find('.portimg ');
if (this.files && this.files[0]) {
var reader = new FileReader();
reader.onload = function (e) {
reset($newinput.next('.delbtn'), true);
$newinput.attr('src', e.target.result).show();
$newinput.after('<div class="delbtn delete_upload" title="Remove"><span class="bbb-icon bbb-i-remove2"></span></div>');
$("form").on('click', '.delbtn', function (e) {
reset($(this));
$("form").find('#rright-<?php echo $i;?>').hide();
});
}
reader.readAsDataURL(this.files[0]);
}
}
$(".file").change(readURL);
function reset(elm, prserveFileName) {
if (elm && elm.length > 0) {
var $input = elm;
$input.prev('.portimg').attr('src', '').hide();
if (!prserveFileName) {
$($input).parent().parent().parent().find('input.file ').val("");
//input.fileUpload and input#uploadre both need to empty values for particular div
}
elm.remove();
}
}
});
</script>
我想要的是调用 Object.createObjectURL(this.files[0]) 来获取对象 URL,并将其用作 img 的 src; (只是不要打扰 FileReader)。
像这样的东西?
function readURL() {
var file = this.files[0]
var reader = new FileReader();
var base64string = getBase64(file);
reader.onload = function () {
reset($newinput.next('.delbtn'), true);
$newinput.attr('src', e.target.result).show();
$newinput.after('<div class="delbtn delete_upload" title="Remove"><span class="bbb-icon bbb-i-remove2"></span></div>');
var blob = dataURItoBlob(base64string);
};
reader.onerror = function (error) {
console.log('Error: ', error);
};
}
我不确定这是否可行,并且由于 Stack Snippets 的变幻莫测,无法在 Stack Overflow 上证明其可行性,但理论上,您应该能够使用URL.createObjectURL
为您的图像创建适当的 URL,无需通过整个 base 64 rigmarole。
var $newinput = $(this).parent().parent().parent().find('.portimg ');
if (this.files && this.files[0]) {
$newinput.attr('src', URL.createObjectURL(this.files[0]));
// if the above doesn't work, you could try to create a new Blob
var fileBlob = new Blob(this.files[0], { type: "image/png" })
// Substitute "image/png" with whatever image type it is
$newinput.attr('src', URL.createObjectURL(fileBlob));
这应该为图像的来源呈现适当的 URL。
请注意,最好的做法是在完成后撤销对象 URL。 我不确定在这种情况下是否有必要,因为大概您想在页面关闭之前显示图像。 但是,如果用户可以上传新图像,请执行以下操作:
if ($newinput.attr('src').indexOf('blob') > -1) {
URL.revokeObjectURL($newinput.attr('src'));
}
在设置新源之前添加它,您无需担心内存泄漏(无论如何使用createObjectURL
......)。
有关blob URL的更多信息,请参阅此答案由现在匿名用户什么是BLOB URL以及为什么使用它?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.