html5ã® File API ã使ã£ã¦ãã¢ãããã¼ãç¡ãã§ç»åãã¬ãã¥ã¼
ç»åããã¬ãã¥ã¼ããããã«ããµã¼ãã¸ã¢ãããã¼ãããå¿
è¦ããªããªãã¾ã*1ã
html
fileã®ã¢ãããã¼ããã©ã¼ã ã«onchangeãä»è¾¼ãã§ããã¾ãã
ãã¨ã¯ããã¬ãã¥ã¼è¡¨ç¤ºç¨ã®è¦ç´ ã ãæºåã
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> </head> <body> <form> <input type="file" name="file" onchange="preview(this)" /> </form> <hr /> <b>preview:</b><br /> <div id="preview_field"></div> </body> </html>
javascript
function preview(ele) { if (!ele.files.length) return; // ãã¡ã¤ã«æªé¸æ var file = ele.files[0]; if (!/^image\/(png|jpeg|gif)$/.test(file.type)) return; // typeããããã£ã§MIMEã¿ã¤ããåç § var img = document.createElement('img'); var fr = new FileReader(); fr.onload = function() { img.src = fr.result; // èªã¿è¾¼ãã ç»åãã¼ã¿ãsrcã«ã»ãã document.getElementById('preview_field').appendChild(img); } fr.readAsDataURL(file); // ç»åèªã¿è¾¼ã¿ // ç»ååã»MIMEã¿ã¤ãã»ãã¡ã¤ã«ãµã¤ãº document.getElementById('preview_field').innerHTML = 'file name: ' + file.name + '<br />' + 'file type: ' + file.type + '<br />' + 'file size: ' + file.size + '<br />'; }
ã¹ãã©ã·ã¤ã