我有一个javascript上传功能,可以将上传的图像转换(并成功显示)为base64代码,如下所示:
data:image / png; base64,iVBORw0KGgoAAAANSUhEUgAAAoAAAARwCAIAAAD17XJXAAAAHGlET ... ZrV0tK9FCERJTNmmAViRoe9QAawjnKAU5LlQhuSeIKVf8 / 0HbUB0ZqCkwAAAAASUVORK5CYII =
js代码来自我在stackoverflow上找到的函数,代码在这里:
readImage: function(file) {
var reader = new FileReader();
var image = new Image();
reader.readAsDataURL(file);
reader.onload = function(_file) {
image.src = _file.target.result; // url.createObjectURL(file);
image.onload = function() {
var w = this.width,
h = this.height,
t = file.type, // ext only: // file.type.split('/')[1],
n = file.name,
s = ~~(file.size/1024) +'KB';
console.log(this.src)
$('#uploadPreview').append('<img src="'+ this.src +'"> '+w+'x'+h+' '+s+' '+t+' '+n+'<br>');
};
image.onerror= function() {
alert('Invalid file type: '+ file.type);
};
};
}
然后我将其作为字符串发布到我的PHP rest API,并执行此操作:
echo base64_decode('data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAoAAAARwCAIAAAD17XJXAAAAHGlET…ZrV0tK9FCERJTNmmAViRoe9QAawjnKAU5LlQhuSeIKVf8/0HbUB0ZqCkwAAAAASUVORK5CYII=');
exit;
但我只看到空白或空白