POPMUISE
有<input type="file" id="picture">你可以为它添加一个事件处理程序来监听change事件(这段代码必须在上面的HTML之后或在DOMContentLoaded事件上注册)var input = document.getElementById('picture');input.addEventListener('change', handleFiles, false);然后你的handleFiles事件会将图像绘制到画布中并从文件中提取base64字符串:function handleFiles(e) {
var canvas = document.createElement('canvas');
var ctx = canvas.getContext('2d');
var img = new Image();
img.onload = function() {
ctx.drawImage(img, 0, 0);
var base64 = canvas.toDataURL();
console.log(base64);
}
img.src = URL.createObjectURL(e.target.files[0]);}运行示例如下:var input = document.getElementById('picture');input.addEventListener('change', handleFiles, false);function handleFiles(e) { var canvas = document.createElement('canvas'); var ctx = canvas.getContext('2d'); var img = new Image(); img.onload = function() { ctx.drawImage(img, 0, 0); var base64 = canvas.toDataURL(); document.getElementById('result').value = base64; } img.src = URL.createObjectURL(e.target.files[0]);}textarea { width: 350px; height: 100px;}<input type="file" id="picture" /><br /> <br /><textarea id="result"></textarea>