我试图在base64字符串中获取图像的内容.
最初我是用readAsDataURL
而不是because I want to validate the mimetype
on the client side做的,似乎我必须使用readAsArrayBuffer,同样指出on this site.
所以我以前工作得很好:
var reader = new FileReader(); reader.onloadend = function(event) { var base64 = reader.result; }; reader.readAsDataURL(event.target.files[0]);
var reader = new FileReader(); reader.onloadend = function(event) { var realMimeType = getRealMimeType(reader); if (realMimeType !== 'unknown') { var emptyBufferArray = reader.result; //nothing }else{ alert("Invalid mime type!"); } }; reader.readAsArrayBuffer(event.target.files[0]); //<-- notice the difference
Reproduction online(没有获取base64字符串)
解决方法
我发现这样做的唯一方法是使用两个不同的FileReader实例,一个在另一个内.
使用Javascript
$(document).on('change','#upload',addBackgroundImage); function addBackgroundImage(event) { var reader = new FileReader(); var readerBase64 = new FileReader(); var image = event.target.files[0]; reader.onloadend = function() { var realMimeType = getRealMimeType(reader); if (realMimeType !== 'unknown') { readerBase64.readAsDataURL(image); } else { alert("Please upload a valid image file"); } }; reader.readAsArrayBuffer(image); readerBase64.onloadend = function(){ var base64 = this.result; $('.bg').css('background-image','url('+base64+')'); }; $('#upload').val(''); } function getRealMimeType(reader){ var arr = (new Uint8Array(reader.result)).subarray(0,4); var header = ''; var realMimeType; for (var i = 0; i < arr.length; i++) { header += arr[i].toString(16); } // magic numbers: http://www.garykessler.net/library/file_sigs.html switch (header) { case "89504e47": realMimeType = "image/png"; break; case "47494638": realMimeType = "image/gif"; break; case "ffd8ffDB": case "ffd8ffe0": case "ffd8ffe1": case "ffd8ffe2": case "ffd8ffe3": case "ffd8ffe8": realMimeType = "image/jpeg"; break; default: realMimeType = "unknown"; // Or you can use the blob.type as fallback break; } return realMimeType; }
HTML
<input type="file" id="upload" /> <div class="bg"></div>